c - 击中返回终止 2 scanf("%[^\n]%*c")
问题描述
我正在尝试读取 2 行用户输入。对于第一个序列,如果我不输入任何内容并按回车键,程序将打印enter the second sequence
但不允许第二个scanf
. 基本上返回只是终止 both scanf
,导致 bothstr1
和str2
空。
printf("enter the first sequence: ");
scanf("%[^\n]%*c", str1);
printf("enter the second sequence: ");
scanf("%[^\n]%*c", str2);
有什么办法可以解决这个问题吗?
解决方案
字符串的格式说明符是%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() 输入中删除尾随换行符感兴趣?
推荐阅读
- python - 查找 Regex 给出多个结果
- ruby - Rspec:错误数量的参数(给定 1,预期为 0)和未定义的方法 `[]' 用于 nil:NilClass
- timer - 在线程组迭代之间添加延迟时间
- python - GCP - apache-beam.io.textio.ReadFromText 给出 SSLHandshakeError: [SSL: CERTIFICATE_VERIFY_FAILED]
- javascript - 带有 Shopify option-select.js 的 Slick 滑块:selectCallback 中的 slickGoTo 导致加载时出现控制台类型错误
- ruby-on-rails - Ruby on Rails:按相关表值排序表
- observer-pattern - 查找文件行的模式,打印行直到第一个空行
- ruby-on-rails - Rails 部署问题:```App 与 buildpack 不兼容:...```
- reactjs - 使用 Jest/Enzyme 进行 FlatList 测试
- c++ - 在 C++ 中将字符串转换为字符