C++文件输入从下一行开始

C++ File Input start from next line

本文关键字:一行 开始 文件 输入 C++      更新时间:2023-10-16

我必须编写一个程序来读取这样的文件:
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;
}

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

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

一种读取&存储第二行(从第一行获取编号后)。

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