#include <stdio.h>
int main()
{
int c, i, wspace, others;
int digits[10];
wspace = others = 0;
for (i=0; i<10; i++){
digits[i] = 0;
}
while ((c =getchar())!=EOF){
if (c >= '0' && c <= '9'){
++digits[c-'0'];
}
else if ( c == ' ' || c == '\n' || c == '\t'){
++wspace;
}
else {
++others;
}
printf("digits: %s", digits);
printf("whitespace: %d, others: %d", wspace, others);
}}
在上面提到的代码中,我试图计算数字,空格和其他输入的数量。但是,当我运行程序时,它会重复打印“数字”。如果我将数字[10]的数据类型设置为'char'并使用'for循环'来打印它,程序工作正常。我目前无法做到这一点,我找不到什么错误。
答案 0 :(得分:1)
在您的代码中,digits
是int
类型的结果。您不能使用%s
格式说明符来打印int
数组。您将使用%d
格式说明符使用循环逐个打印元素。
根据C11
标准文件,第7.21.6.1章,fprintf()
函数
s
如果不存在l length修饰符,则参数应为指向初始值的指针 字符数组的元素。
OTOH,如果您将digits
更改为char
类型的数组,则可以使用%s
。在这种情况下,无需使用循环逐个打印。
注意:int
数组不是字符串。
编辑:
即使您将digits
数组更改为char
类型,在使用%s
打印数组时也可能无法获得所需的输出。请注意,0
和'0'
不一样。
0
的ASCII值为0
,代表nul
。'0'
的ASCII值为48
,表示字符 0
。解决方案:根据当前的方法,您需要使用int
格式指定的循环逐个打印%d
元素。