homer512 icon

input parsing II

homer512 | PRO | 03/08/15 05:13:57 PM UTC | 0 ⭐ | 684 👁️ | Never ⏰ | []
C++ |

1.01 KB

|

None

|

0 👍

/

0 👎

#include <fstream>
// using std::ifstream
#include <iostream>
// using std::cout, std::cerr
#include <vector>
// using std::vector
#include <string>
// using std::string, std::getline
#include <utility>
// using std::pair
 
 
int main()
{
  std::vector<std::pair<std::string, int> > values;
  const char* fname = "house_repairs.txt";
  std::ifstream input(fname);
  if(! input) {
    std::cerr << "unable to open " << fname << std::endl;
    return 1;
  }
  while(input) {
    std::string header;
    int value;
    if(std::getline(input, header) >> value >> std::ws)
      values.push_back(std::make_pair(header, value));
  }
  if(! input.eof()) {
    std::cerr << "IO error after " << values.size() << " key value pairs"
          << std::endl;
    return 1;
  }
  for(std::vector<std::pair<std::string, int> >::iterator i = values.begin();
      i != values.end(); ++i) {
    (std::cout << "Got " << i->first).put('\t');
    (std::cout << i->second).put('\n');
  }
  std::cout.flush();
  return 0;
}

Comments