开发者

How to read in space-delimited information from a file in c++

开发者 https://www.devze.com 2022-12-25 08: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?std::i

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?


std::ifstream file("filename");
std::vector<int> array;
int number;
while(file >> number) {
    array.push_back(number);
}


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号