Advertisement
homer512

C++ input parsing

Mar 7th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 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.  
  10.  
  11. int main()
  12. {
  13.   std::vector<std::string> keys;
  14.   std::vector<int> values;
  15.   const char* fname = "house_repairs.txt";
  16.   std::ifstream input(fname);
  17.   if(! input) {
  18.     std::cerr << "unable to open " << fname << std::endl;
  19.     return 1;
  20.   }
  21.   while(input) {
  22.     /* first attempt to read an integer. If that fails, it must be a key */
  23.     int value;
  24.     if(input >> value)
  25.       values.push_back(value);
  26.     else if(input.fail()) {
  27.       input.clear();
  28.       std::string line;
  29.       if(std::getline(input, line))
  30.     keys.push_back(line);
  31.     }
  32.     if(input.bad()) {
  33.       std::cerr << "IO error" << std::endl;
  34.       return 1;
  35.     }
  36.   }
  37.   for(std::vector<std::string>::iterator i = keys.begin(); i != keys.end();
  38.       ++i)
  39.     (std::cout << "Got key " << *i).put('\n');
  40.   for(std::vector<int>::iterator i = values.begin(); i != values.end(); ++i)
  41.     (std::cout << "Got value " << *i).put('\n');
  42.   std::cout.flush();
  43.   return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement