首页 > 解决方案 > 击中返回终止 2 scanf("%[^\n]%*c")

问题描述

我正在尝试读取 2 行用户输入。对于第一个序列,如果我不输入任何内容并按回车键,程序将打印enter the second sequence但不允许第二个scanf. 基本上返回只是终止 both scanf,导致 bothstr1str2空。

printf("enter the first sequence: ");
scanf("%[^\n]%*c", str1);

printf("enter the second sequence: ");
scanf("%[^\n]%*c", str2);

有什么办法可以解决这个问题吗?

标签: cstringscanfc99

解决方案


字符串的格式说明符是%s,所以只需使用它:

printf("enter the first sequence: ");
scanf("\n%s", str1);

printf("enter the second sequence: ");
scanf("\n%s", str2);

正如@AjayBrahmakshatriya 评论的那样:\n匹配任意数量的\n字符。

使用 scanf 读取 char 时的问题%c在于它将换行符视为输入,正如我在此示例中所解释的那样。


但是,如果我是你,我会使用fgets(),如下所示:

fgets(str1, sizeof(str1), stdin);
fgets(str2, sizeof(str2), stdin);

如果您采用这种方法,您可能会对从 fgets() 输入中删除尾随换行符感兴趣?


推荐阅读