fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stdexcept>
  5.  
  6. struct itemInfo
  7. {
  8. int quantity;
  9. std::string name;
  10. double price;
  11. };
  12.  
  13. std::istream& operator>>(std::istream &in, itemInfo &item)
  14. {
  15. try
  16. {
  17. std::string line;
  18.  
  19. if (std::getline(in, line))
  20. {
  21. auto start = line.find_first_not_of(" \t");
  22. auto stop = line.find_first_of(" \t", start + 1);
  23. item.quantity = std::stoi(line.substr(start, stop - start));
  24.  
  25. start = line.find_first_not_of(" \t", stop + 1);
  26. stop = line.find(" at ", start);
  27. item.name = line.substr(start, stop - start);
  28.  
  29. start = line.find_first_not_of(" \t", stop + 4);
  30. item.price = std::stod(line.substr(start));
  31. }
  32. }
  33. catch (const std::logic_error &)
  34. {
  35. in.setstate(std::ios_base::failbit);
  36. }
  37.  
  38. return in;
  39. }
  40.  
  41. int main()
  42. {
  43. itemInfo item;
  44. std::vector<itemInfo> items;
  45.  
  46. while (std::cin >> item)
  47. {
  48. items.push_back(item);
  49. }
  50.  
  51. // use items as needed...
  52.  
  53. for(auto &item : items)
  54. {
  55. std::cout << item.name << ": " << item.quantity << " @ " << item.price << std::endl;
  56. }
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5436KB
stdin
1 toy at 10.65
2  box of books at 12.11
1 pot plant at 6.45
stdout
toy: 1 @ 10.65
box of books: 2 @ 12.11
pot plant: 1 @ 6.45