Advertisement
homer512

input parsing II

Mar 8th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <fstream>
  2. // using std::ifstream
  3. #include <iostream>
  4. // using std::cout, std::cerr
  5. #include <vector>
  6. // using std::vector
  7. #include <string>
  8. // using std::string, std::getline
  9. #include <utility>
  10. // using std::pair
  11.  
  12.  
  13. int main()
  14. {
  15.   std::vector<std::pair<std::string, int> > values;
  16.   const char* fname = "house_repairs.txt";
  17.   std::ifstream input(fname);
  18.   if(! input) {
  19.     std::cerr << "unable to open " << fname << std::endl;
  20.     return 1;
  21.   }
  22.   while(input) {
  23.     std::string header;
  24.     int value;
  25.     if(std::getline(input, header) >> value >> std::ws)
  26.       values.push_back(std::make_pair(header, value));
  27.   }
  28.   if(! input.eof()) {
  29.     std::cerr << "IO error after " << values.size() << " key value pairs"
  30.           << std::endl;
  31.     return 1;
  32.   }
  33.   for(std::vector<std::pair<std::string, int> >::iterator i = values.begin();
  34.       i != values.end(); ++i) {
  35.     (std::cout << "Got " << i->first).put('\t');
  36.     (std::cout << i->second).put('\n');
  37.   }
  38.   std::cout.flush();
  39.   return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement