Skip to content

Instantly share code, notes, and snippets.

@bryangoodrich
Last active August 29, 2015 14:25
Show Gist options
  • Save bryangoodrich/dd435a1fc37bc5d7d9d2 to your computer and use it in GitHub Desktop.
Save bryangoodrich/dd435a1fc37bc5d7d9d2 to your computer and use it in GitHub Desktop.
Reverse an integer text input stream.
/*********************************************************************
* Compilation: g++ -std=c++11 reverse.cpp -o reverse.exe
* Execution: reverse.exe < input.txt
*
* Reverse an integer text input stream
*
* This is a toy code snippet for using C++11 types to handle
* an input stream, store the incoming data by line, and reverse
* it while printing to standard output.
*
* The to_int wrapper is because std::stoi would not be recognized
* by my compiler, even with the -std=c++11 flag.
*
* The input file used for this came from
* http://algs4.cs.princeton.edu/11model/tinyT.txt
*
* $ head tinyT.txt
* 23
* 50
* 10
* 99
* 18
* 23
* 98
* 84
* 11
* 10
* $ reverse.exe < tinyT.txt
* 68 77 77 98 54 13 77 48 10 11 84 98 23 18 99 10 50 23
*
*********************************************************************/
#include <iostream> // std::cout, std::cin, std::getline
#include <string> // std::string, std::stoi
#include <list> // std::list
#include <cstdlib> // atoi
int to_int(std::string s)
{
return atoi(s.c_str());
}
int main ( )
{
std::list<int> v;
for (std::string s; std::getline(std::cin, s); )
{
int value = to_int(s);
v.push_front(value);
}
for (auto itr = v.begin(), end = v.end(); itr != end; ++itr)
{
std::cout << *itr << " ";
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment