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

半腔热情 提交于 2019-12-20 02:01:30

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2530738/how-to-read-in-space-delimited-information-from-a-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!