c - c中的格式说明符值问题

标签 c format-specifiers

int friends = 20;

printf("I have %d friend%c", friends , (friends !=1 ? "s" : ""));

return 0;

所以每当我运行代码时,它都会调试到这里

I have 20 friend$

当我在 friend 之后使用 %s 格式说明符运行它时,它工作正常。 s 只是一个字符,为什么它不起作用?

最佳答案

那么为什么它不起作用? 因为 %c 需要 char 但表达式 (friends !=1 ? "s ": "") 结果为字符串(双引号)。所以要么使用 %s 这样的

printf("I have %d friend%s", friends , (friends !=1 ? "s" : ""));

或者

"s" 替换为 's' 并将 "" 替换为 ' ' as % c 需要 char

printf("I have %d friend%c", friends , (friends !=1 ? 's' : ' '));

关于c - c中的格式说明符值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104483/

相关文章:

c - printf中的 "%.*s"是什么意思?

c - fscanf 不扫描任何数字

string - $d 在 printf 中做什么?

c - 双除法不断给我 "inf"

c - 为什么 printf() 不将此整数输出为 float ?

C:计数字母直到插入特定条目

c - 这里与字符串比较是什么意思?

c - 为什么使用 %c 和 %d 格式化时此 C 代码的输出不同

c - 将 strcpy() 与 strtok 一起使用

c - 在以下 c 代码中出错 [段错误]