您好,我将从文件中读取并将用空格分隔的数字放入不同的数组中。 要读取的示例文件
15
10 2
20 1
30 1
这是我做的
while(!file.eof()){
file>>first[count++];
}
通过这样做,我逐行读取,但我想读取直到出现空白并将空白之后的数字放入不同的数组中。 结果数组将如下所示(假设 first 和 second 是动态整数数组)
first={15,10,20,30}
second ={0,2,1,1}
最佳答案
你应该使用 string streams .
#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);
}
}
这里,first
和second
被假定为 vector
关于c++ - 将由空格分隔的文件读入动态数组C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018935/