Andrei Ciobanu
Andrei Ciobanu

Reputation: 12840

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 

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 ?

Upvotes: 5

Views: 10855

Answers (3)

Howard Hinnant
Howard Hinnant

Reputation: 218700

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

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

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

Upvotes: 5

ardiyu07
ardiyu07

Reputation: 1800

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)

Upvotes: 1

Related Questions