Suppose a text file has hello\n stack overflow \n in a file, the output should be 2 since there are 2 \n sequences. Instead, I am getting one as the answer. What am I doing wrong? Here is my code:
int main()
{
FILE *fp = fopen("sample.txt", "r"); /* or use fopen to open a file */
int c; /* Nb. int (not char) for the EOF */
unsigned long newline_count = 1;
/* count the newline characters */
while ( (c=fgetc(fp)) != EOF ) {
if ( c == '\n' )
newline_count++;
putchar(c);
}
printf("\n %lu newline characters\n ", newline_count);
return 0;
}
Try this:
Really, a literal
\nis two characters (a string), not just one. So you cannot simply compare it as though it was a character.EDIT
Since
\nis two characters, the\and then, we must remember the last character we read in, and check if the current character is annand the previous character is a\. If both tests are true, that means we have located the sequence\nin the file.