在C中将字符添加到字符串的末尾

时间:2015-12-18 23:22:30

标签: c

我想在字符串的末尾添加文本。为什么我的代码下面的任何想法都不起作用?

#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);
}

1 个答案:

答案 0 :(得分:6)

两个问题:

  • scanf("%s", &text);应为scanf("%19s", text);,因为text已经是字符数组的地址。 19用于确保输入适合text缓冲区,为\0字符留出至少一个空格。
  • 当您使用strlen时,需要正确的标题<string.h>

正如BLUEPIXY所指出的,if (text[i] == '\0')永远不会为真,因为strlen不包含\0字符。