#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::ifstream data("data.txt");
std::string line;
std::vector<int> v;
while (std::getline(data, line)) {
v.clear();
std::istringstream parse(line);
int i;
while (parse >> i)
v.push_back(i);
std::sort(v.begin(), v.end());
for (int o : v)
std::cout << o << " ";
std::cout << std::endl;
}
std::cout << "Press Enter to exit";
std::cin.get();
return 0;
}
Excellent Patrik! This works right out of the box when I add, "-std=c++11" to the compiler options ([Error] range-based-for loops not allow in C98 mode). Thanks you
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream iss(line);
v.clear();
int i;
while (iss >> i)
v.push_back(i);
std::sort(v.begin(), v.end());
for (auto x : v)
std::cout << x << ' ';
std::cout << '\n';
}
}
EDIT: Note that even most of the variables have the same names!!! The biggest difference between the two programs seems to be that I work in a Unix style --where it's natural to read from standard input and write to standard output-- and he probably works on Windows.
Thanks Alvaro,
I had something close to this but abandoned the whole idea when I encountered a compiler error about range-based for loops. I got your's to work also with a little bit of changes.
jhaglund2 wrote:Excellent Patrik! This works right out of the box when I add, "-std=c++11" to the compiler options ([Error] range-based-for loops not allow in C98 mode). Thanks you
I like to use a little helper class called "line", so that I can use iterators to read /write from std::cin/std::cout and also to read/write from the intermediate stringstream: