Read line of numbers using C++

本小妞迷上赌 提交于 2019-12-17 20:38:36

问题


What's the standard way of reading a "line of numbers" and store those numbers inside a vector.

file.in
12 
12 9 8 17 101 2 

Should I read the file line by line, split the line with multiple numbers, and store the tokens in the array ?

What should I use for that ?


回答1:


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

std::vector<int> data;
std::ifstream file("numbers.txt");
std::copy(std::istream_iterator<int>(file), std::istream_iterator<int>(), std::back_inserter(data));



回答2:


Here's one solution:

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>

int main()
{
    std::ifstream theStream("file.in"); 
    if( ! theStream )
          std::cerr << "file.in\n";
    while (true)
    {
        std::string line;
        std::getline(theStream, line);
        if (line.empty())
            break;
        std::istringstream myStream( line );
        std::istream_iterator<int> begin(myStream), eof;
        std::vector<int> numbers(begin, eof);
        // process line however you need
        std::copy(numbers.begin(), numbers.end(),
                  std::ostream_iterator<int>(std::cout, " "));
        std::cout << '\n';
    }
}



回答3:


std::cin is the most standard way to do this. std::cin eliminates all whitespaces within each number so you do

while(cin << yourinput)yourvector.push_back(yourinput)

and they will automatically be inserted to a vector :)

EDIT:

if you want to read from file, you can convert your std::cin so it reads automatically from a file with:

freopen("file.in", "r", stdin)


来源:https://stackoverflow.com/questions/5005317/read-line-of-numbers-using-c

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