I have the following text file:
0 0 0 0 0 1 0 0 2 3 4 2 1 2 1
0 0 0 0 2 7 5 4 5 7 5 4 3
3 2 4 6 2 7 2 7 5 4 5 7 5 4 3
3 2 4 6 2 7 2 7 5 4 5 4 3
0 0 0 0 0 1 0 2 3 4 2 1 2 1
0 0 0 0 0 1 0 0 2 3 4 2 1 2 1
0 0 0 0 2 1 2 1
3 2 4 6 2 7 2 7 5 4 5 7 5 4 3
3 2 4 6 2 0 2 3 4 2 1 2 1
0 0 0 0 0 1 0 0 2 3 4 2 1 2 1
3 2 4 6 2 7 2 7 5 4 5 7 5 4 3
I can read it with the following program:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::ifstream is("numbers.txt");
std::string line;
std::vector<std::vector<int>> numbers{};
while (std::getline(is,line)) {
std::stringstream ss{line};
std::istream_iterator<int> start{ss},end;
numbers.emplace_back(start,end);
std::cout << "Read " << numbers.back().size() << " numbers in row\n";
}
std::cout << "Read " << numbers.size() << " rows\n";
std::cout << "numbers read in:\n";
for (auto row : numbers) {
for (auto number : row) {
std::cout << number << " ";
}
std::cout << "\n";
}
std::cout << std::endl;
}
I would like to create the std::stringstream
and std::istream_iterator
only once outside the loop. How could I adjust the iterator to the correct position each time the loop executes in the following program?
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::ifstream is("numbers.txt");
std::string line;
std::vector<std::vector<int>> numbers{};
std::stringstream ss{line};
std::istream_iterator<int> start{ss},end;
while (std::getline(is,line)) {
ss << line;
//start = ss.beg;
numbers.emplace_back(start,end);
std::cout << "Read " << numbers.back().size() << " numbers in row\n";
}
std::cout << "Read " << numbers.size() << " rows\n";
std::cout << "numbers read in:\n";
for (auto row : numbers) {
for (auto number : row) {
std::cout << number << " ";
}
std::cout << "\n";
}
std::cout << std::endl;
}
Aucun commentaire:
Enregistrer un commentaire