fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <iomanip>
  4.  
  5. struct Person {
  6. unsigned int id;
  7. std::string name;
  8. uint8_t age;
  9. // ...
  10. };
  11.  
  12. struct delim_field_extractor_proxy;
  13.  
  14. struct delim_field_extractor_proxy {
  15. delim_field_extractor_proxy(std::string& field_ref, char delim = '"')
  16. : field_ref_(field_ref), delim_(delim) {}
  17.  
  18. friend
  19. std::istream& operator>>(std::istream& is, const delim_field_extractor_proxy& extractor_proxy);
  20.  
  21. void extract_value(std::istream& is) const {
  22. field_ref_.clear();
  23. char input;
  24. bool addChars = false;
  25. while(is) {
  26. is.get(input);
  27. if(is.eof()) {
  28. break;
  29. }
  30. if(input == delim_) {
  31. addChars = !addChars;
  32. if(!addChars) {
  33. break;
  34. }
  35. else {
  36. continue;
  37. }
  38. }
  39. if(addChars) {
  40. field_ref_ += input;
  41. }
  42. }
  43. // consume whitespaces
  44. while(std::isspace(is.peek())) {
  45. is.get();
  46. }
  47. }
  48. std::string& field_ref_;
  49. char delim_;
  50. };
  51.  
  52.  
  53. std::istream& operator>>(std::istream& is, const delim_field_extractor_proxy& extractor_proxy) {
  54. extractor_proxy.extract_value(is);
  55. return is;
  56. }
  57.  
  58. int main() {
  59. std::istream& ifs = std::cin; // Open file alternatively
  60. std::vector<Person> persons;
  61.  
  62. Person actRecord;
  63. int act_age;
  64. while(ifs >> actRecord.id
  65. >> delim_field_extractor_proxy(actRecord.name,'"')
  66. >> act_age) {
  67. actRecord.age = uint8_t(act_age);
  68. persons.push_back(actRecord);
  69. }
  70.  
  71. for(auto it = persons.begin();
  72. it != persons.end();
  73. ++it) {
  74. std::cout << it->id << ", " << it->name << ", " << int(it->age) << std::endl;
  75. }
  76. return 0;
  77. }
Success #stdin #stdout 0s 3480KB
stdin
1267867 "John Smith"         32   
67545     "Jane Doe"           36  
8677453 "Gwyneth Miller"   56  
75543     "J. Ross Unusual" 23  
stdout
1267867, John Smith, 32
67545, Jane Doe, 36
8677453, Gwyneth Miller, 56
75543, J. Ross Unusual, 23