/* stringlength
* input: str, pointer to a string
* output: integer representing the length of string str,
* not counting the terminating character.
*
* You may NOT call ANY functions within this function.
*/
int stringlength(char *str)
{
// count the number of characters in str
int count=0,k;
for (k=0; str[k] != '\0';k++)
count++;
return count;
}
/* countchars
* inputs: character c, string str
* output: The number of instances of c in the string str
* You may not call ANY function calls within this function.
*/
int countchars(char c, char *str)
{
// count the number of times c is found in str
int k,count=0;
for (k=0;str[k]=='\0';k++)
{
if (str[k] == c)
count++;
else;
}
return count;
}
/* countlines
* input: char *filename - string containing the filename
* output: integer representing the number of lines in the file
*/
int countlines(char *filename)
{
// count the number of lines in the file called filename
FILE *f = fopen(filename,"r");
char ch;
int lines=0;
f = fopen(filename,"r");
do{
ch = fgetc(f);
if( ch == '\n')
lines++;
}while( ch != EOF );
return lines;
}
I need help with these three different functions that I am implementing in my program. I am a beginner so go easy on me, the countlines function is giving me the most trouble. If anyone could explain why not or why these functions will work, it would be greatly appreciated.
There are a number of problems in
countlines():You open the file twice, but overwrite the first
FILE *value with the second, so there’s no way you can close it. This is a minor problem.The major problem is that the function
fgetc()returns anint, not achar. In particular,EOFis a value different from everychar.The code does not close the file before returning. Generally, if you open a file in a function, then you should close it. If you don’t, you have to pass the file pointer back to the calling code so that it can close it.
The
do ... whileloop is seldom correct for an input loop (awhileloop testing at the top is almost always much cleaner and clearer) but at least you weren’t usingfeof().When you use
charinstead, one of two things happens:chartype issigned, then a real character (often ÿ — y-umlaut, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS) also matchesEOFso you can stop reading before you reach end of file.chartype isunsigned, no value will ever matchEOFso the loop will never stop.In
stringlength(), you have two variablescountandkthat are carefully kept at the same value; you only need one of the two.Apart from raggedy indentation (endemic in the code shown — and definitely something to be avoided), and the unnecessary and pointless
else;which does absolutely nothing, the code forcountchars()looks OK(late addition) … has the condition in theforloop inverted; it should bestr[k] != '\0', of course.