作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试读取包括空格在内的字符数。
我使用 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;
}
当我测试输入(带空格)时,例如
最佳答案
定义一个 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/
我是一名优秀的程序员,十分优秀!