[英]I need to read new line characters in a file
假设一个文件文件在文件中有hello\\n stack overflow \\n
,输出应为2
因为有2个\\n
序列。 相反,我得到一个作为答案。 我究竟做错了什么? 这是我的代码:
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;
}
试试这个:
int main()
{
FILE *fp = fopen("sample.txt", "r"); /* or use fopen to open a file */
int c, lastchar = 0; /* Nb. int (not char) for the EOF */
unsigned long newline_count = 0;
/* count the newline characters */
while ( (c=fgetc(fp)) != EOF ) {
if ( c == 'n' && lastchar == '\\' )
newline_count++;
lastchar = c; /* save the current char, to compare to next round */
putchar(c);
}
printf("\n %lu newline characters\n ", newline_count);
return 0;
}
真的,文字\\n
是两个字符(一个字符串),而不仅仅是一个字符。 所以你不能简单地将它比作一个角色。
编辑因为\\n
是两个字符, \\
和n
,我们必须记住我们读入的最后一个字符,并检查当前字符是否为n
,前一个字符是否为\\
。 如果两个测试均为真,则表示我们已将序列\\n
在文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.