开发者

Read line of numbers using C++

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 

S开发者_开发问答hould 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 ?


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


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜