打印字符串时出错
Error in printing a string
#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);
}}
在上述代码中,我试图计算数字、空格和其他输入的数量。但是,当我 运行 程序时,它会重复打印 'digits'。如果我将 digits[10] 的数据类型设置为 'char' 并使用 'for loop' 打印它,程序就可以正常工作。我找不到我目前的做法有什么问题。
在您的代码中,digits
是一个 int
类型的数组。您不能使用 %s
格式说明符来打印 int
数组。您必须使用 %d
格式说明符使用循环逐个打印元素。
根据 C11
标准文档,第 7.21.6.1 章,fprintf()
函数
s
If no l length modifier is present, the argument shall be a pointer to the initial
element of an array of character type.
OTOH,如果将 digits
更改为 char
类型的数组,则可以使用 %s
。在那种情况下不需要使用循环来逐一打印。
注意:int
的数组不是 字符串。
编辑:
即使您将 digits
数组更改为 char
类型,您在使用 %s
打印数组时也可能无法获得所需的输出。请记住,0
和 '0'
是不一样的。
0
的 ASCII 值为 0
,表示 nul
.
'0'
的 ASCII 值为 48
,表示 字符 0
.
解决方案:根据当前方法,您必须使用循环使用 %d
格式规范逐个打印 int
个元素。
#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);
}}
在上述代码中,我试图计算数字、空格和其他输入的数量。但是,当我 运行 程序时,它会重复打印 'digits'。如果我将 digits[10] 的数据类型设置为 'char' 并使用 'for loop' 打印它,程序就可以正常工作。我找不到我目前的做法有什么问题。
在您的代码中,digits
是一个 int
类型的数组。您不能使用 %s
格式说明符来打印 int
数组。您必须使用 %d
格式说明符使用循环逐个打印元素。
根据 C11
标准文档,第 7.21.6.1 章,fprintf()
函数
s
If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.
OTOH,如果将 digits
更改为 char
类型的数组,则可以使用 %s
。在那种情况下不需要使用循环来逐一打印。
注意:int
的数组不是 字符串。
编辑:
即使您将 digits
数组更改为 char
类型,您在使用 %s
打印数组时也可能无法获得所需的输出。请记住,0
和 '0'
是不一样的。
0
的 ASCII 值为0
,表示nul
.'0'
的 ASCII 值为48
,表示 字符0
.
解决方案:根据当前方法,您必须使用循环使用 %d
格式规范逐个打印 int
个元素。