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