【问题标题】:I can't read the second string, no matter how many getchar i insert我无法读取第二个字符串,无论我插入多少 getchar
【发布时间】:2015-10-30 23:38:41
【问题描述】:

这个程序需要读取两个字符串,这两个字符串将被传递给“确认”函数,它们将被读取并且函数必须找到一个共同的单词。

但主要我无法读取“string2”字符串!无论我插入多少 getchar。

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

void confirm(char string1[],char string2[]){

    char word[20];
    char w_aux[20];
    int i, j, k, l, m;
    int len1, len2;
    int find;

    i = 0; 

    len1 = strlen(string1);
    len2 = strlen(string2);

    while (i < len1){
        j = 0;

        while ((string1[i] != ' ') && (i < len1)){
            word[j] = string1[i];
            i++;
            j++;
        }
        word[j] = '\0';
        k = 0;
        find = 0;
        while((k < len2) && (find == 0)){ 

            l = 0;
            while ((string2[k] != ' ') && (k < len2)){
                w_aux[l] = string2[k];
                k++;
                l++;
            }
            w_aux[l] = '\0';        
            if (j == l){
                m = 0;
                while((word[m] == w_aux[m]) && (m<j)){
                    m++;
                }
                if (m == j){
                    find = 1;
                }
            }
            k++;
        }
        i++;
    }
    printf("%s\n", word);
}

int main (){

    char string1[20];
    char string2[20];

    printf("Type the first text: \n");
    scanf("%[^\n]s", string1);

    printf("Type the second text: \n");
    scanf("%[^\n]s", string2);
    getchar();


    confirm(string1, string2);

    return 0;
}

【问题讨论】:

  • sscanf() 格式中的作用是什么?
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 MCVE 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。您应该显示输入和输出,以及您已完成的调试结果。

标签: c string getchar


【解决方案1】:

在为\n输入字符串1后使用getchar

printf("Type the first text: \n");
scanf("%[^\n]", string1);

getchar(); //here

printf("Type the second text: \n");
scanf("%[^\n]", string2);

【讨论】:

  • @MateusLuiz 在输入 string1 后,您按下 '\n' 换行符,该换行符被 string2 接受并且程序终止,为了接受这个尾随换行符,我们使用 getchar()
【解决方案2】:

只需将格式说明符更改为"%19[^\n]*c",它将去掉结尾的'\n' 字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多