【问题标题】:C++ File Input start from next lineC++ 文件输入从下一行开始
【发布时间】:2014-10-11 14:53:30
【问题描述】:

我必须编写一个程序来读取这样的文件:
7
5 6 4 2 1 3 8

第一行表示有多少人,第二行表示每个人的身高。我设法读取了第一行并将其存储在一个变量中,但是如何继续第二行单独读取每个整数(它们用空格分隔)

using namespace std;

int rowNum;


int main()
{
    fstream myfile;
    string rowNumT;

    myfile.open ("xxx_in.txt",ios::in | ios::out);
    if(myfile.is_open()){
        while(getline(myfile,rowNumT)){
            //cout << rowNumT ;
            istringstream (rowNumT) >> rowNum;
            cout << rowNum ;//how many children in integer form

        }
    }
    else cout << "Unable to open file";

    int heights[rowNum];

    myfile.close();
    return 0;
}

【问题讨论】:

  • 你甚至不需要getline。直接从文件中一次读取一个数字。

标签: c++ arrays file input output


【解决方案1】:

无需解析字符串和额外的高度,简单使用:-

int npeople ;
int height ;
// std::vector<int> heights ; // Use std::vector
myfile >> npeople ;

while ( myfile >> height )
{
   // Use height ;
   // heights.push_back ( height );
}

myfile >> npeople ;
std::vector<int> heights ;
std::copy( std::istream_iterator<int>( myfile ), 
           std::istream_iterator<int>(),
           std::back_inserter( heights )
          ) ;

另外,可以使用C++11实现以下功能:

myfile >> npeople ;
std::vector<int> heights { std::istream_iterator<int>( myfile ), 
                           std::istream_iterator<int>() 
                         };

【讨论】:

    【解决方案2】:

    一种读取和存储第二行的方法(从第一行获取数字后)。

    std::ifstream infile("file.txt");
    std::string line;
    
    while (std::getline(infile, line))
    {
      std::istringstream iss(line);
      int n;
      std::vector<int> v;
    
      while (iss >> n)
      {
        v.push_back(n);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多