Read files by character C++

2019-08-08 16:22发布

问题:

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)

回答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.



回答2:

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