1

I wanted to read a file with numbers ex:

2
2 3 
2 3 4 
5 6 7

3 
2 2
1 2 
2 3 

I used the getline () function and I store the results in a vector (string). However, when I access the elements in the vector, the entire line with spaces were stored. I wanted to store elements by number (the numbers represent a matrix)

Josh
  • 3,231
  • 8
  • 37
  • 58
  • To read a number: `int x;stream >> x`. There are many question on SO about reading numbers from a stream: http://stackoverflow.com/search?q=C%2B%2B+reading+a+number&submit=search A bit of research before asking is always a good idea. – Martin York Feb 11 '12 at 15:41
  • possible duplicate of [dynamical two dimension array according to input](http://stackoverflow.com/questions/2216017/dynamical-two-dimension-array-according-to-input) – Martin York Feb 11 '12 at 15:43

2 Answers2

3

You can use just stream::operator >> for that.

int x;
cin >> x;

or with file stream:

#include <fstream>

int main()
{
    std::ifstream f("input.txt");
    int x;
    f >> x;
    std::cout << x;
    return 0;
}
Lol4t0
  • 12,444
  • 4
  • 29
  • 65
  • how can I use cin to read from a file? wouldn't I have to somehow link cin to read from a file? – Josh Feb 11 '12 at 16:01
  • @Josh, `cin` is just an example. `cin` _is a stream_ and you can use another stream instead of `cin` – Lol4t0 Feb 11 '12 at 16:10
1
#include<fstream>
#include<iterator>
#include<vector>

int main(int, char*[])
{
    std::ifstream file("numbers.txt");
    std::vector<int> data((std::istream_iterator<int>(file)),
                          std::istream_iterator<int>());
}

will give you a vector of integers.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131