简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM