且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 int 添加到字符串时遇到问题,尝试使用 sprintf 但我遇到了问题

更新时间:2023-11-14 17:24:34

如果需要字符,请在 C 中使用 %c 作为格式说明符.如果您使用 %d,它将起作用,但会显示为整数.
另一件事是,如果要使用 sprintf 将字符串与 char 或 int 连接起来,则必须将两者都包含在 sprintf 的参数列表中:

Use a %c for a format specifier in C if you want the character. if you use %d, it will work, but will display as integer.
The other thing is that if you want to use sprintf to concatenate a string with a char, or and int, you must include both in the argument list of sprintf:

改变这个:

sprintf(word, "%d", c);

为此:

char newString[20];//adjust length as necessary
sprintf(newString, "%s%c",word, c);  

你在这里的逻辑表明你只想附加字符,如果它是一个 alpha [a-z,A-Z]

Your logic here suggests that you only want to append the char, if it is an alpha [a-z,A-Z]

  if(isalpha(c))
  {
    //strcat(word, &c);
    sprintf(word, "%d", c);
    continue;
  }  

改为:

  if(isalpha(c))
  {
    //strcat(word, &c);
    char newString[20];//bigger if needed, 20 just for illustration here
    sprintf(newString, "%s%d", word, c);
    continue;
  }