如何从c或C ++中的命令行读取多行输入? [英] How to read a multiple line input from command line in c or C++?

查看:460
本文介绍了如何从c或C ++中的命令行读取多行输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



1 20



2 31



3 41



>我使用类似

  int main()
{
string line;

while(getline(cin,line)!= NULL)
{
//一些代码
//一些代码
}


}

现在程序永远不会停止, 。在没有更多输入行的情况下,如何创建循环?

解决方案

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

  #include< iostream> 
#include< string>

使用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;
}
//一些代码
}
return 0;
}


For Example: If I need to read a multiple line input like(and I dont know How many lines would be there!!):

1 20

2 31

3 41

I am using something like

int main()
{
  string line;

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


}

Now the program never stops- i.e always it expects some input. How do i beak the loop when there are no more input lines ?

解决方案

Just test the variable line for empty each time you read a line. If the use presses enter with no other data, then line will be empty.

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

这篇关于如何从c或C ++中的命令行读取多行输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆