How to read in space-delimited information from a

2019-02-24 12:10发布

In a text file I will have a line containing a series of numbers, with each number separated by a space. How would I read each of these numbers and store all of them in an array?

2条回答
2楼-- · 2019-02-24 12:45
std::ifstream file("filename");
std::vector<int> array;
int number;
while(file >> number) {
    array.push_back(number);
}
查看更多
干净又极端
3楼-- · 2019-02-24 12:51

Just copy them from the stream to the array:

#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::ifstream file("filename");
    std::vector<int> array;

    std::copy(  std::istream_iterator<int>(file),
                std::istream_iterator<int>(),
                std::back_inserter(array));
}
查看更多
登录 后发表回答