gpt4 book ai didi

将 gets() 更改为 txt 文件输入

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

我需要使用 gets() 将这段代码从用户输入转换为扫描输入 txt 文件。找到一种方法来计算每个单词中字母的数量也会很有帮助。从 1 个字母的单词开始,依次类推。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


int main(void) {

int acount, bcount, ccount, dcount, ecount, fcount, gcount, hcount, icount, jcount, kcount, lcount, mcount, ncount, ocount, pcount, qcount, rcount, scount, tcount, ucount, vcount, wcount, xcount, ycount, zcount = 0;
char *str;

printf("Enter any string : ");
gets(str);

while (*str != '\0')
{
if(isalpha(*str))
{
toupper(*str);
switch(*str)
{
case 'A':
++acount;
break;

case 'B':
++bcount;
break;

case 'C':
++ccount;
break;

case 'D':
++dcount;
break;

case 'E':
++ecount;
break;

case 'F':
++fcount;
break;

case 'G':
++gcount;
break;

case 'H':
++hcount;
break;

case 'I':
++icount;
break;

case 'J':
++jcount;
break;

case 'K':
++kcount;
break;

case 'L':
++lcount;
break;

case 'M':
++mcount;
break;

case 'N':
++ncount;
break;

case 'O':
++ocount;
break;

case 'P':
++pcount;
break;

case 'Q':
++qcount;
break;

case 'R':
++rcount;
break;

case 'S':
++scount;
break;

case 'T':
++tcount;
break;

case 'U':
++ucount;
break;

case 'V':
++vcount;
break;

case 'W':
++wcount;
break;

case 'X':
++xcount;
break;

case 'Y':
++ycount;
break;

case 'Z':
++zcount;
break;

}//Close case
}//Close if
}//Close while

printf("Number of A's: %d", acount);

}

最佳答案

代码中有很多错误

  1. 您不必将所有 (x)count 变量初始化为 0,请阅读有关逗号运算符的信息。

  2. 您使用了 gets(),这是一个卑鄙且已弃用的函数。

  3. 您向 gets() 传递了一个未初始化的指针,这是未定义的行为。

  4. toupper(*str) 不会修改 *str

试试这个

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void)
{
/* You need an array of int's with size equal to the number of letters
* int the alphabet
*/
int count['Z' - 'A' + 1];
/* You need some space to store the text, `str' will become a poitner
* when you pass it to `fgets()' pointing to an array of 1000 `chars'
*/
char str[1000];
/* Initialize all the counters to 0 */
for (int i = 0 ; i < sizeof(count) / sizeof(*count) ; ++i)
count[i] = 0;
printf("Enter any string : ");
/* Read the string, use `fgets()` and prevent a buffer overflow */
if (fgets(str, sizeof(str), stdin) == NULL)
return -1;
/* Now count the letters */
for (int i = 0 ; ((str[i] != '\0') && (str[i] != '\n')) ; ++i)
{
/* If it's not a letter, go to the next one */
if (isalpha((int) str[i]) == 0)
continue;
/* It's a letter, count it at the correct position */
count[toupper((int) str[i]) - 'A'] += 1;
}

/* Print the count of each letter, skipping those that did not appear */
for (int i = 0 ; i < sizeof(count) / sizeof(*count) ; ++i)
{
if (count[i] == 0)
continue;
fprintf(stderr, "Number of %c's : %d\n", i + 'A', count[i]);
}
return 0;
}

关于将 gets() 更改为 txt 文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724971/

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