gpt4 book ai didi

c - 如何在不使用字符串的情况下通过 scanf 读取具有多个字符的用户输入

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:34 25 4
gpt4 key购买 nike

我正在为一门类(class)开发一个程序,该程序需要读取用户输入的一行并计算该行中每个字母的数量。每个字母的数量放在一个数组中。例如,如果用户输入“Apple”,程序应将 1 a、2 ps、1 l 和 1 e 放入计数数组。我的问题是我的教授说我不能在程序中使用字符串。我不确定如何存储多个字符以便 scanf 可以在不使用字符串的情况下读取它们。寻求帮助时,他说一次读取输入的一个字符。

我曾尝试在 do-while 循环中使用 scanf 来读取输入的每个字符,但我的大部分尝试都只是以仅读取第一个字符并将其放入记录字母数的数组中而告终。

printf("ENTER A LINE OF TEXT: \n");
do {
scanf("%c ", &userChar);
userChar = toupper(userChar);
userCharVal = userChar;
histo[userCharVal - 65] = histo[userCharVal - 65] + 1;
} while(userChar == '\n');

如果用户输入“apple”,相应的数组 histo[] 将根据输入的字母进行更新。我。 e.如果用户输入apple,程序会先将histo[0](对应'a')加1,然后读取单词的下一个字符。它应该在换行处结束读取用户输入。实际上,程序只是记录第一个字符,然后结束。

最佳答案

你的问题是

while(userChar == '\n');

当您在 "Apple" 中读取 'A' 时,userChar 不会 == '\n' 导致你的 oop 在第一次迭代后终止。您的意图是:

while(userChar != '\n');

(注意 "!=" 而不是 "==")

有了它,您的代码应该可以工作,尽管没有必要使用单独的 userCharuserCharVal

要稍微清理一下,只需使用一个 int 来通过 getchar() 读取字符,不需要 scanf (最好避免)。需要的额外验证是字符是 [a-zA-Z],以确保您使用 histo[userCharVal - 65] 递增有效索引。 (当您可以使用 'A' 清楚地表明您在做什么时,请避免使用像 65 这样的数字)

总而言之,你可以做类似的事情:

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

#define NCHR 26 /* to cover each character in the alphabet */

int main (void) {

int frequency[NCHR] = {0}, /* frequency of each char initialized to zero */
c; /* character returned by getchar() */

fputs ("enter a line of text: ", stdout);
while ((c = getchar()) != '\n' && c != EOF) /* read each char */
if (isalpha(c)) /* validate a-zA-Z */
frequency[toupper(c) - 'A']++; /* increment element */

puts ("\nfrequency of characters:\n");
for (c = 0; c < NCHR; c++)
if (frequency[c]) /* output lowercase per your example */
printf (" %c : %d\n", c + 'a', frequency[c]);
}

(注意还需要对 EOF 进行额外检查。不保证 '\n' 用户可以生成在 Linux 上使用 Ctrl+d 或在 Windows 上使用 Ctrl+z 的手动 EOF 表示输入结束,或完全取消输入那件事)

示例使用/输出

$ ./bin/charfreqarray
enter a line of text: Apple

frequency of characters:

a : 1
e : 1
l : 1
p : 2

检查一下,如果您还有其他问题,请告诉我。

关于c - 如何在不使用字符串的情况下通过 scanf 读取具有多个字符的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604221/

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