#include <stdio.h>
#include <string.h>
main() {
int i;
char given[30];
char reversed[30];
printf("enter your stringn");
scanf("%s", given);
for (i = 0; i <= (strlen(given)); i++) {
if (i <= (strlen(given) - 1)) {
reversed[i] = given[(strlen(given) - 1 - i)];
} else {
reversed[i] = given[i];
}
}
printf("%s", reversed);
return 0;
}
字符串
当我运行这段代码时,如果我给予输入作为123
,它将返回321
,但当我将123 325
作为输入时,它将只给出321
作为输出(它应该是523 321
)。为什么会这样呢?
2条答案
按热度按时间huus2vyu1#
对于初学者,函数
main
应该显式指定返回类型int
(或兼容)字符串
至于你的问题那么根据C标准(7.21.6.2
fscanf
函数;这同样适用于scanf
)s
匹配一个非空白字符序列。也就是说,一旦遇到白色字符,就停止填充用作参数表达式的相应字符数组。非白色字符的读取序列以空字符
'\0'
结束。因此,只有来自用户输入的第一个单词123
被程序读取和反转,如果你有一个循环,输入行的其余部分将由另一个对scanf()
的调用读取。如果要读取包含白色字符的字符串,则需要使用另一种转换规范,例如:
型
还要注意,多次调用函数
strlen
是低效的。你也应该在使用变量的最小范围内声明变量。
您的程序可以看起来像下面这样
型
ecfsfe2w2#
%s
不会读取整行。看看here。%s
的条目表示为Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
也许How do you allow spaces to be entered using scanf?或How to read one whole line from a text file using
<
?可以为您提供替代方案。