我正在尝试读取字符数,包括空格。 我使用 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/