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

时间:2010-06-18 08:39:47

标签: c++ c command-line

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

1 20

2 31

3 41

我正在使用像

这样的东西
int main()
{
  string line;

  while(getline(cin,line) != NULL)
  {
       // some code
       // some code    
  }


}

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

5 个答案:

答案 0 :(得分:4)

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

#include <iostream>
#include <string>

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;
}

答案 1 :(得分:2)

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

#include <stdio.h>
#include <stdlib.h>

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;
}

答案 2 :(得分:1)

在Linux上 - C-d(或Ctrl + D)输出EOF字符,这将终止你的循环。

做像......这样的事情要容易得多。

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

答案 3 :(得分:0)

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

答案 4 :(得分:-1)

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
      }
   }
相关问题