c - 为什么我的 %[^\n] 不能正常工作?

标签 c

int main() {
    char a[100];

    printf("\nEnter 1st Sentence : ");
    scanf("%[^\n]", a);
    printf("\nSentence 1 : %s", a);

    printf("\nEnter 2nd Sentence : ");
    scanf("%[^\n]", a);
    printf("\nSentence 2 : %s", a);

    return 0;
}

我的输出:

Enter 1st Sentence : Testing 1st Sentence
Sentence 1 : Testing 1st Sentence
Enter 2nd Sentence : 
Sentence 2 : Testing 1st Sentence

我基本上是在检查%[^\n]。当我输入第一个句子并按“Enter”键时,它会打印“Enter 2nd Sentence :”,然后打印“Sentence 2 :”,然后打印第一个句子。

最佳答案

因为您没有从输入缓冲区读取 Enter 键,所以当第二个 scanf() 请求输入时,它仍然存在。然后它认为您只是按下了 Enter 键而没有输入任何文本。

关于c - 为什么我的 %[^\n] 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302511/

相关文章:

char *c = "12.3"我如何将 12.3 存储到 double 变量中

c - 如何在 Linux 上设置串口中断?

c - 迭代具有编号名称的对象

c - 作用域如何影响同名的全局和局部结构?

c - 变长数组;另一个构造 MSVC 无法编译?

C语言或编程

c - 如何正确地逐字节读取文件而不丢失任何信息

c - strtok 只保存第一个标记的问题

c - 内存泄漏,段错误,C

c - 在 gtk+3 中向 GtkTextBuffer 添加数字