[英]C programming: counts the number of characters, words and lines from another text file
我刚刚开始学习C语言,正如本主题所说,我必须编写一个代码,该代码将读取另一个文本文件并计算“字符”,“单词”和“句子”的数量,直到达到EOF
。 我当前的问题是我无法产生正确的输出。
例如,包含以下内容的文本文件...
the world
is a great place.
lovely
and wonderful
应该输出39个字符,9个单词和4个句子,以某种方式我得到50个(字符)1个(单词)1个(句子)
这是我的代码:
#include <stdio.h>
int main()
{
int x;
char pos;
unsigned int long charcount, wordcount, linecount;
charcount = 0;
wordcount = 0;
linecount = 0;
while(pos=getc(stdin) != EOF)
{
if (pos != '\n' && pos != ' ')
{
charcount+=1;
}
if (pos == ' ' || pos == '\n')
{
wordcount +=1;
}
if (pos == '\n')
{
linecount +=1;
}
}
if (charcount>0)
{
wordcount+=1;
linecount+=1;
}
printf( "%lu %lu %lu\n", charcount, wordcount, linecount );
return 0;
}
感谢您的任何帮助或建议
由于运算符的优先级,下面的2行相同。
// Not what OP needs
pos=getc(stdin) != EOF
pos=(getc(stdin) != EOF)
而是使用()
while((pos=getc(stdin)) != EOF)
使用int ch
来区分从fgetc()
返回的值,它们是unsigned char
范围和EOF
。 通常有257种不同,对于char
来说太多了。
int main() {
unsigned long character_count = 0;
unsigned long word_count = 0;
unsigned long line_count = 0;
unsigned long letter_count = 0;
int pos;
while((pos = getc(stdin)) != EOF) {
...
您可能还需要查看您的字数统计策略。 @托尼·坦诺斯
对于我来说,我会把一个“单词”视为出现在未跟随非字母的字母的任何时间。 这样可以避免@Tony Tannous和其他问题。 同样,我会将一行视为'\\n'
或第一个字符之后的任何字符,并避免进行任何后循环计算。 这可以处理Weather Vane所评论的问题。
它还显示39是字母计数而不是字符计数@BLUEPIXY 。
建议使用<ctype.h>
函数测试字母性( isapha()
)
int previous = '\n';
while((pos = getc(stdin)) != EOF) {
character_count++;
if (isalpha(pos)) {
letter_count++;
if (!isalpha(previous)) word_count++;
}
if (previous == '\n') line_count++;
previous = pos;
}
printf("characters %lu\n", character_count);
printf("letters %lu\n", letter_count);
printf("words %lu\n", word_count);
printf("lines %lu\n", line_count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.