[英]How do I get number of characters in each line?
I need to get number of characters in each line and then paste it into another file (school project) but even my prototype is already not working. 我需要获取每一行中的字符数,然后将其粘贴到另一个文件(学校项目)中,但是甚至我的原型也无法正常工作。
I have already trying continuing seeing whether problem resolves itself when I paste it into another file but it didn't work so I'm back to this. 我已经尝试继续查看问题,将其粘贴到另一个文件中后是否可以解决,但是它没有用,所以我回到了这一点。
int main()
{
FILE *fw;
FILE *fr;
int i = 0;
char c;
fr = fopen("vstup.txt","r");
fw = fopen("vystup.txt","w");
while ((c = getc(fr)) != EOF)
{
while ((c = getc(fr)) != '\n')
{
i++;
}
printf("%d\n", i);
}
}
c
has to be declared int
, not char
. 必须将
c
声明为int
,而不是char
。 EOF
might not be a valid char
value, so the inequality might succeed forever. EOF
可能不是有效的char
值,因此不等式可能永远成功。
You shouldn't call getc()
twice. 您不应两次调用
getc()
。 You never check the result of the first call to see if it's a newline. 您永远不会检查第一个调用的结果是否是换行符。
You need to set i
back to 0
after you read a newline, otherwise you'll keep adding the next line's length to the previous line. 阅读换行符后,需要将
i
设置为0
,否则将继续将下一行的长度添加到上一行。
You should only print the length when you read a newline, not every time through the loop. 仅在读取换行符时才打印长度,而不是每次循环时都打印长度。 And if the last line doesn't end with newline, you should print its length after the loop;
而且如果最后一行不是以换行符结尾,则应在循环之后打印其长度; you can tell this happened if
i
is not 0
when it's done. 如果
i
完成时i
不为0
,就可以知道发生了这种情况。
Since the lengths should be written into the other file, you should use fprintf()
. 由于应将长度写入另一个文件,因此应使用
fprintf()
。
while ((c=getc(fr)) != EOF) {
if (c == '\n') {
printf("%d\n", i);
i = 0;
} else {
i++;
}
}
if (i != 0) {
fprintf(fw, "%d\n", i);
}
You don't need a nested loop. 您不需要嵌套循环。 You need to zero out the counter either way, so you may as well just use an
if
instead of a while: 您需要以任何一种方式将计数器归零,因此您最好只使用
if
而不是一会儿:
int main()
{
FILE *fw, *fr;
int count = 0;
int c;
fr = fopen("vstup.txt","r");
fw = fopen("vystup.txt","w");
while ((c = getc(fr)) != EOF) {
count++;
if(c == '\n') {
fprintf(fw, "%d\n", count);
count = 0;
}
}
fclose(fr);
fclose(fw);
}
This version will count newlines as valid characters. 此版本会将换行符视为有效字符。
Note that c
must be an int
, not a char
, so that it can hold every character value returned by getc
as well as EOF
, which is not a character value. 请注意,
c
必须是int
,而不是char
,以便它可以容纳getc
返回的每个字符值以及EOF
,而不是字符值。
And don't forget to close your files! 并且不要忘记关闭文件!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.