使用 2 scanf("%[^\n]s") 但第二个被跳过

Using 2 scanf("%[^\n]s") but the second one is getting skipped

int main(){

     char str1[20], str2[20];
    printf("Enter string 1 : ");
    scanf("%[^\n]s",str1);

    printf("Enter string 2 : ");
    scanf("%[^\n]s",str2);

    printf("String 1 is %s\n",str1);
    printf("String 2 is %s\n",str2);
    removeFromSecond(str1,str2);
}

输出为:

Enter string 1 : in

Enter string 2 : String 1 is in

String 2 is ■   a

只是不要求输入第二个字符串。 我不记得了,但我在某处读到过我们需要添加一行来吃掉所有未使用的 '\n'。 拜托,如果有人知道,我需要那行。

第二个 scanf("%[^\n]s",str2); 无法保存任何内容,因为前一行的 '\n' 未被先前的 scanf("%[^\n]s",str1); 或此 scanf("%[^\n]s",str2);.

消耗

要阅读用户输入的 ,请使用 fgets()

// scanf("%[^\n]s",str1);
fgets(str1, sizeof str1, stdin);

由于 fgets() 也读取并保存了一个潜在的 '\n',如果它存在,请使用下方将其删除。

str1[strcspn(str1, "\n")] = 0;

scanf() 很少是好的选择。在你明白为什么它不好之前不要使用。


如果_必须使用scanf(),去掉格式中没用的s,加一个width:

// Ugly POS code
char str1[20] = "";  // Set to empty string in case nothing saved
// Read up to 19 non-\n characters.  If more available, read them but don't save.
scanf("%19[^\n]%*[^\n]",str1);  
// consume up to 1 trailing \n, do not save.
scanf("%*1[\n]");

// TBD check return values.

好吧,就像每个人告诉我的那样使用 fgets(),因为它是正确的选择。但是,如果有人想知道我实际提出的问题的答案,就像风向标在评论中所说的那样这是菜鸟的错误,只需在第二次 scanf.

的 % 之前添加一个 space

喜欢scanf("%[^\n]", str2); -> 至 -> scanf(" %[^\n]", str2);