gpt4 book ai didi

arrays - 如何从C中的输入中读取字符数?

转载 作者:行者123 更新时间:2023-12-04 08:54:01 25 4
gpt4 key购买 nike

我正在尝试读取包括空格在内的字符数。
我使用 scanf 函数来检查使用 %c 的字符。另外附带说明,我将如何将输入存储到数组中?

#include <stdio.h>

int main(void) {
char n, count= 0;

while (scanf("%c", &n) != EOF) {
count = count+1;
}

printf("%d characters in your input \n", count);

return 0;
}
当我测试输入(带空格)时,例如
abcdefg
它不打印任何东西。

最佳答案

定义一个 MAX_CHAR 并在循环中检查它可以防止无效的内存写入。
请记住,如果要打印或使用 char 数组,则数组的最后一个字节应保留为 '\0'。

#include <stdio.h>
#define MAX_CHAR 100

int main(void) {

char n[MAX_CHAR]={0}, count= 0;

while((count!=MAX_CHAR-1)&&(scanf("%c",&n[count])==1))
{
if((n[count]=='\n')){
n[count]=0;
break;
}
count++;
}

printf("%d characters in your input [%s]\n", count, n);

return 0;
}

关于arrays - 如何从C中的输入中读取字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63945280/

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