fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <cstdlib>
  4. #include <vector>
  5. #include <map>
  6.  
  7. struct Phone {
  8. std::string type;
  9. std::string color;
  10. int price;
  11. };
  12.  
  13. std::vector<Phone> parsePhoneFromString(const std::string& s);
  14.  
  15. int main()
  16. {
  17. std::string lineIn = "Lt36/tim3080,d3000,t3010,lt35/2870,mt35/d1915,t1920,"
  18. "lt29/1905,lt28h/d1810,h1790,lt25/t1810,lt26ii/t1920,"
  19. "d1910,lt26w/1340,lt26i/t1740,d1730,lt22/d1420,h1370,"
  20. "b1370,s36h/1380";
  21. auto phones = parsePhoneFromString(lineIn);
  22. for (auto& phone : phones)
  23. std::cout << phone.type << " "
  24. << phone.color << " "
  25. << phone.price << "\n";
  26. }
  27.  
  28.  
  29. std::vector<Phone> parsePhoneFromString(const std::string& s)
  30. {
  31. //cần thêm -std=c++11 vào compiler flags
  32. static std::map<std::string,std::string> colorMap = {
  33. {"t","trắng"}, {"h","hồng"},{"b","bạc"}, {"tim", "tím"},
  34. {"","đen"}, {"d","đen"} //ai chạy windows thì bỏ dấu đi
  35. };
  36. std::istringstream iss(s);
  37. Phone phone;
  38. std::string temp;
  39. std::vector<Phone> result;
  40.  
  41. while (getline(iss,temp,','))
  42. {
  43. size_t islash = temp.find('/');
  44. if (islash!=temp.npos) {
  45. phone.type = temp.substr(0,islash);
  46. temp = temp.substr(islash+1);
  47. }
  48. size_t idigit = 0;
  49. while (!isdigit(temp[idigit])) ++idigit;
  50. phone.color = colorMap.at(temp.substr(0,idigit));
  51. phone.price = atoi(temp.substr(idigit).c_str());
  52. result.push_back(phone);
  53. }
  54. return result;
  55. }
Success #stdin #stdout 0s 3440KB
stdin
Standard input is empty
stdout
Lt36  tím  3080
Lt36  đen  3000
Lt36  trắng  3010
lt35  đen  2870
mt35  đen  1915
mt35  trắng  1920
lt29  đen  1905
lt28h  đen  1810
lt28h  hồng  1790
lt25  trắng  1810
lt26ii  trắng  1920
lt26ii  đen  1910
lt26w  đen  1340
lt26i  trắng  1740
lt26i  đen  1730
lt22  đen  1420
lt22  hồng  1370
lt22  bạc  1370
s36h  đen  1380