gpt4 book ai didi

c - 将 scanf 和 EOF 添加到程序中

转载 作者:行者123 更新时间:2023-11-30 15:28:24 38 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>

int main()
{
char string[100];
int c = 0, count[26] = {0};
int accum = 0;

printf("Enter a string\n");
gets(string);

while ( string[c] != '\0' )
{

if ( string[c] >= 'a' && string[c] <= 'z' ){
count[string[c]-'a']++;
accum++;
}

else if (string[c] >= 'A' && string[c] <= 'Z'){
count[string[c]-'A']++;
accum++;
}
c++;
}

for ( c = 0 ; c < 26 ; c++ )
{
if( count[c] != 0 )
printf( "%c %f\n", c+'a', ((double)count[c])/accum);
}

return 0;
}

这应该是一个简单的问题,但我似乎无法让它发挥作用。现在,我有打印语句“输入字符串”。我想更改它,以便用户可以继续使用 scanf 而不是 printf 输入字符串,直到到达 EOF。基本上我想删除“输入字符串”语句,只输入一个字符串直到 EOF,然后在所有输入的字符串上运行一次字母频率。我该怎么做?

最佳答案

使用 scanf() 输入来执行此操作。

scanf() 当 EOF 条件或 IO 错误发生时返回 EOF。

 // printf("Enter a string\n");
char ch;
while (scanf("%c", &ch) == 1) {
if ( ch >= 'a' && ch <= 'z' ){
count[ch-'a']++;
accum++;
}
...
}

使用int ch = fgetc(stdin)会更有意义。

<小时/>

"The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure." C11dr §7.21.6.2 16

关于c - 将 scanf 和 EOF 添加到程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594906/

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