在字符串中附加一个字符,然后在c中删除并打印该字符串

时间:2019-01-18 20:53:12

标签: c

我正在尝试编写一个程序,将您给它的字母附加到当前字符串中。我几乎在每个领域都有问题,好像我尝试添加字母一样,这给了我一个“细分错误”。我已经添加了评论,每个部分应该做什么,希望对这个项目有所帮助。

  #include <stdio.h>
  #include <string.h>

        int main(void) {
        int choice;
        char str[20];
        char str1;

    while(1) {
        printf("Give your choice: "); //Asks the choice from the menu
        scanf("%i", &choice);

        if(choice == 1) { //This choice adds a letter to the (empty) string
            printf("Give a letter: ");
            scanf("%s", str); 
            strcat(str, str1); }

        else if(choice == 2) { //choice 2 clears the string
            printf("");
            scanf("%s", str1); }

        else if(choice == 3) { //choice 3 prints what's in the string
            printf("%s", str1); }

        else { //if choice is wrong, it ends the program
            printf("Faulty input!\n");
            break; }

        }   }

谢谢!

1 个答案:

答案 0 :(得分:2)

  

此选择将字母添加到(空)字符串

scanf("%s", str); 
strcat(str, str1);

在这里,您不是要在现有字符串中添加字母,而是清除字符串并重新输入。 将char传递给strcat也会导致未定义的行为,因为strcat期望其参数为char *并且 null 终止。


将其更改为如下。

scanf(" %c", &str1); //Takes single char
int len = strlen(str); //Finds the length
str[len] = str1; // Appends the char
str[len + 1] = '\0'; //null terminates the string
相关问题