C 计算行、字和字符数
我是编程新手。我正在尝试编写一个程序,从文本文件中读取行、字和字符。下面是代码C 计算行、字和字符数,c,C,我是编程新手。我正在尝试编写一个程序,从文本文件中读取行、字和字符。下面是代码 #include "stdio.h" #include "stdlib.h" #define IN 1 #define OUT 0 int main (int argc, char *argv[]) { FILE *input; int character, newword, newline, state; char c; state = OUT; character =
#include "stdio.h"
#include "stdlib.h"
#define IN 1
#define OUT 0
int main (int argc, char *argv[]) {
FILE *input;
int character, newword, newline, state;
char c;
state = OUT;
character = newline = newword =0;
input = fopen(argv[1], "r");
if ( input == NULL){
printf("Error! Can not read the input\n");
exit(-1);
}
while ((c = fgetc(input)) != EOF){
character++;
if (c <'a' && c >'z'){;}
if ( c <'A' && c >'Z'){;}
if (c == '\n'){
newline++;
}
if (c == ' ' || c == '\n' || c == '\t'){
state = OUT;
}
else if (state == OUT){
state = IN;
newword++;
}
}
printf("The number of lines: %d\n", newline);
printf("The number of words: %d\n", newword);
printf("The number of characters: %d\n", character);
fclose(input);
}
并在终端输出:
The number of lines: 2
The number of words: 5
The number of characters: 7
但是,如果我取出两个for循环(c<'A'和&c>'Z')
和(c<'A'和&c>'Z')
,则输出变为
The number of lines: 2
The number of words: 1
The number of characters: 7
是否有任何解决此问题的提示(我不想要答案!)?您的if必须类似于:
if ('a' <= c && c <='z'){character++;}
else if ( 'A' <= c && c <='Z'){character++;}
if('a'解决问题的最简单方法是,当字符位于间隔'a'和'z'之间或间隔'a'和'z'之间时,增加字符计数器,然后,由于转义序列'\n'创建了一个新行,这也意味着您正在处理一个新词,因此您也应该增加此计数器。最后,您可以选中空格或水平选项卡以增加新词计数器
if ((c <'a' && c >'z') || ( c <'A' && c >'Z')){
++character;
}
else if (c == '\n'){
++newline;
++newword;
}
else if (c == ' ' || c == '\t'){
++newword;
}
if((c'z')| |(c'z')){
++性格;
}
else如果(c=='\n'){
++新线;
++新词;
}
else如果(c=''| | c=''\t'){
++新词;
}
c'z'
始终为false。简而言之,如果文件包含标点符号,您无法阻止程序读取标点符号。您必须处理它。您可以决定如何计数。通常,单词之间用空格(空格、制表符、换行符等)隔开。任何非空白的内容都是“单词”的一部分。您可以优化您的选择-例如,您可以忽略标点符号。您应该查找标题
和函数(宏),例如isalpha()
和ispunt()
和isspace()
。您还可以查找GNU实用程序的源代码wc
并查看它的工作原理。您可能会注意到序列if(c'z'){;}if(c'z'){;}if(c='\n'){
始终针对'a'
和'z'
运行测试,并针对'a'
和'z'
运行测试(这两个测试都有严重的缺陷),然后针对'\n'
运行测试。如果不希望所有三个测试都运行,则应在第二个和第三个测试中使用else If
:If(c'z'){…}else If(c'z'){…}else If(c='\n'){…}
等等。此外,您必须使用int c;
,而不是char c;
。这是因为getchar()
返回一个int
,该值介于0和255之间(通常假设char\u位==8
),或额外的EOF值(通常为负值,但不一定为-1
)。由于8位char
不能表示257个值,因此会发生以下两种情况之一:(1)如果char
是有符号类型,则有效字符(有时ÿU+00FF拉丁文小写字母Y带DIAERESIS)被视为与EOF相同,因此输入会提前停止,或(2)如果char
是无符号类型,则!=EOF
条件始终为真,循环不会停止。
if ((c <'a' && c >'z') || ( c <'A' && c >'Z')){
++character;
}
else if (c == '\n'){
++newline;
++newword;
}
else if (c == ' ' || c == '\t'){
++newword;
}