gpt4 book ai didi

计算行数、单词数和字符数

转载 作者:行者123 更新时间:2023-11-30 20:12:13 25 4
gpt4 key购买 nike

我是编程新手。我正在尝试编写一个从文本文件中读取行、单词和字符的程序。这是下面的代码。

#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);
}

我一直在试图弄清楚如何不读取特殊字符,例如 ! , @ , # , $ , % , ^ , & , * , ( , ) , _ , + .

我尝试使用 if 语句,因此它不会读取特殊字符,但它会读取它。我认为大写字母的 if 语句是错误的,因为它可能不会读取小写字母。

文件中包含以下文本,

!!.

它在终端中输出:

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++;}

关于计算行数、单词数和字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com