将空格分隔的文件读取到动态数组C++中

Reading file seperated by white spaces into dynamic array C++

本文关键字:动态 数组 C++ 读取 空格 分隔 文件      更新时间:2023-10-16

嗨,我将从文件中读取并将用空格分隔的数字放入不同的数组中。要读取的示例文件

15
10 2
20 1
30 1

这就是我所做的

    while(!file.eof()){ 
        file>>first[count++];
    }

通过这样做,我逐行读取,但我想读取直到空格并将空格之后的数字放入不同的数组中。结果数组将如下所示(假设第一个和第二个是动态整数数组)

first={15,10,20,30}
second ={0,2,1,1}

你应该使用字符串流。

#include <sstream>
...
string line;
while(getline(file, line))
{
   istringstream iss(line);
   int firstNumOnLine, secondNumOnLine.
   iss >> firstNumOnLine;
   first.push_back(firstNumOnLine);
   if(iss >> secondNumOnLine)
   {
        //... 
        second.push_back(secondNumOnLine)
   }
   else
   {
       //... there was no second number on the line.
       second.push_back(0);
   }
}

这里,firstsecond被假定为向量