如何计算文本文件中的段落数 [英] how to count the number of paragraphs in a text file
本文介绍了如何计算文本文件中的段落数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我试过这个
Hi i tried like this
int main()
{
FILE *fp=fopen("200_content.txt ","r");
int pCount=0;
char c;
while ((c=fgetc(fp))!=EOF)
{
if(c=='\n'){pCount++;}
else{continue;}
}
printf("%d",pCount);
return 0;
}
但是我得到了分段错误。任何人都可以帮我这个吗?
But i am getting segmentation fault.Can anyone help me with this?
推荐答案
首先,从文件名中删除空格,然后检查文件是否与可执行文件位于同一文件夹中 - 否则它将无效。
然后,< b>检查你的返回值来自fopen - 因为如果找不到文件,fopen会返回null并且你的代码会失败,如你所见。
然后,看看你的代码吧!你认为这是做什么的:
First, remove the space from your file name, and check the file is in the same folder as the executable - or it won't work.
Then, check your return value from fopen - because if it doesn't find the file, fopen returns null and your code fails, as you have seen.
Then, look at your code! What do you supposed this does:
else{continue;}
这在形式或形式上有用吗?
That is in any way shape or form useful?
一个段落包含两个后续'\ n',使用一个用于计算两个'\\ n'的变量,像这样,
A paragraph contains two subsequent '\n's, use a variable for counting the two '\n's, like this,
int main()
{
FILE *fp=fopen("200_content.txt ","r");
int pCount=0;
char c;
int newln_cnt=0;
while ((c=fgetc(fp))!=EOF)
{
if(c=='\n')
{
newln_cnt++;
if(newln_cnt==2)
{
pCount++;
newln_cnt=0;
}
}
else{continue;}
}
printf("%d",pCount);
return 0;
}
对于初学者,我假设您将新行视为新段落。即
这是第1行。
这是第2行。
有2个段落。
你的代码所做的是忽略了在第2行之后有EOF而不是换行符(\ n)的情况。
修复此问题的一种方法是使用额外的char变量。
For starters, I assume that you consider a new line to be a new paragraph. i.e.
This is line 1.
This is line 2.
has 2 paragraphs.
What your code does is neglect the case where there is an EOF and not a newline character (\n) after This is line 2.
One way to fix this is to use an extra char variable.
int main()
{
FILE *fp=fopen("200_content.txt ","r");
int pCount=0;
char c; // char that checks
char last_c; //record of the last character read in the loop
while ((c=fgetc(fp))!=EOF)
{
if(c=='\n'){pCount++;}
last_c = c;
else{continue;} //this line is redundant. You can remove it
}
if (last_c != '\n') pCount++; //if EOF at the end of line and not '\n'
printf("%d",pCount);
return 0;
}
这篇关于如何计算文本文件中的段落数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文