如何在c或C ++中从命令行读取多行输入?

例如:如果我需要读取多行输入(并且我不知道会有多少行!!):

1 20

2 31

3 41

我正在使用类似的东西

int main() { string line; while(getline(cin,line) != NULL) { // some code // some code } } 

现在程序永远不会停止 – 即总是需要一些输入。 当没有更多输入线时,我如何在循环中喙?

每次读取line ,只需将变量line测试为空。 如果使用按下输入而没有其他数据,则line为空。

 #include  #include  using std::cin; using std::getline; using std::string; int main(int argc, char *argv[]) { string line; while (true) { getline(cin, line); if (line.empty()) { break; } // some code } return 0; } 

请注意,直接在stdin上使用scanf并不是很安全。 例如,输入任何无法解析为数字的内容都会使循环挂起。 这是一个更强大的实现,它首先读取整行,然后尝试从中解析数字。

 #include  #include  int main(void) { char * line = NULL; size_t sz = 0; while(!feof(stdin)) { ssize_t ln = getline(& line, & sz, stdin); if(ln > 0) { int x, y; if(sscanf(line, "%d %d", & x, & y) == 2) printf("x = %i, y = %i\n", x, y); else puts("invalid input"); } } return EXIT_SUCCESS; } 

在linux上 – Cd(或Ctrl + D)输出EOF字符,它将终止你的循环。

这样做更容易……

 ~ $ cat sample.input | my_cool_program output will be displayed here. 

只需插入一个特殊的输入结束命令,然后逐行解析其余的命令。 您无法自动检测输入结束,因为无法知道用户是真正完成输入还是只是浏览或说话或者其他任何情况 – 这完全是系统外部环境。

 while (true) { long value1; long value2; int nofValuesRead; nofValuesRead = scanf("%ld %ld\n",&value1,&value2); if (nofValuesRead==0) break; if (nofValuesRead>=1) { // Process value1 } if (nofValuesRead>=2) { // Process value2 } }