我想在字符串的末尾添加文本。为什么我的代码下面的任何想法都不起作用?
#include <stdio.h>
int main() {
char text[20];
int i;
printf("Enter a text\n");
scanf("%s", &text);
printf("\n\n");
for (i = 0; i < strlen(text); i++) {
printf("%c", text[i]);
if (text[i] == '\0') { //There seems to be something wrong with '\0'
printf("This is the end of this string");
}
}
return(0);
}
答案 0 :(得分:6)
两个问题:
scanf("%s", &text);
应为scanf("%19s", text);
,因为text
已经是字符数组的地址。 19
用于确保输入适合text
缓冲区,为\0
字符留出至少一个空格。strlen
时,需要正确的标题<string.h>
正如BLUEPIXY所指出的,if (text[i] == '\0')
永远不会为真,因为strlen
不包含\0
字符。