打印字符串时出错

时间:2015-04-08 17:16:46

标签: c arrays string char printf

#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循环'来打印它,程序工作正常。我目前无法做到这一点,我找不到什么错误。

1 个答案:

答案 0 :(得分:1)

在您的代码中,digitsint类型的结果。您不能使用%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元素。