c - 如何从 C 中的标准输入读取多行字符串?
问题描述
我是 C 编程的新手。假设我想从标准输入读取多行字符串。我怎样才能继续阅读直到仅包含 EOL 的行?
输入示例
1+2\n
1+2+3\n
1+2+3+4\n
\n (stop at this line)
似乎当我直接按 enter(EOL) 时,scanf将不会执行,直到输入 EOL 以外的其他内容。我该如何解决这个问题?
如果有人可以帮助我,我将不胜感激。谢谢你。
解决方案
If you want to learn C, you should avoid scanf
. The only use cases where scanf
actually makes sense are in problems for which C is the wrong language. Time spent learning the foibles of scanf is not well spent, and it doesn't really teach you much about C. For something like this, just read one character at a time and stop when you see two consecutive newlines. Something like:
#include <stdio.h>
int
main(void)
{
char buf[1024];
int c;
char *s = buf;
while( (c = fgetc(stdin)) != EOF && s < buf + sizeof buf - 1 ){
if( c == '\n' && s > buf && s[-1] == '\n' ){
ungetc(c, stdin);
break;
}
*s++ = c;
}
*s = '\0';
printf("string entered: %s", buf);
return 0;
}
推荐阅读
- awk - 有没有办法用 sed 替换所有逗号,除了引号中的逗号
- arrays - 为什么在 C 中迭代这样的数组效率低下?
- sql - SQL查询查找每个客户的第一条记录并更新
- java - 重命名“main”方法并从其他类调用会导致错误
- javascript - Webpack 捆绑使用另一个包含 WebAssembly 的库的库会提供几个文件作为输出,但它们的路径不是相对的
- r - R:将数据框列名自动连接到向量
- roslyn - 将参考程序集添加到 Roslyn 分析器代码修复单元测试
- markdown - 如何让代码语法突出显示在 Google Codelab 中工作?
- firebase - Firebase 安全规则 - 未定义的资源错误
- r - 在 R 中使用 for 循环遍历数据帧的名称