fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. void print_city_totals( std::istream& input, std::ostream& output )
  6. {
  7. constexpr char COMMA = ',' ;
  8.  
  9. std::string line ;
  10. while( std::getline( input, line ) ) // for each line input the input stream
  11. {
  12. std::istringstream stm(line) ;
  13.  
  14. double first ;
  15. stm >> first ; // get the first number
  16.  
  17. stm.ignore( 100, COMMA ) ; // throw away the comma
  18.  
  19. std::string city_name ;
  20. std::getline( stm, city_name, ',' ) ; // read everything upto the comma into name
  21.  
  22. double second ;
  23. stm >> second ; // get thesecond number
  24.  
  25. if(stm) output << city_name << ' ' << first+second << '\n' ;
  26. else output << "[ error in line: '" << line << "' ]\n" ;
  27. }
  28. }
  29.  
  30. int main()
  31. {
  32. std::istringstream input( "15.1,Chico,17.4\n"
  33. "34.4,Seattle,30.52\n"
  34. "what is this?\n"
  35. "2.9,Portland,26.1\n"
  36. ".5,Death Valley,1.1\n" ) ;
  37.  
  38. print_city_totals( input, std::cout ) ;
  39. }
  40.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Chico 32.5
Seattle 64.92
[ error in line: 'what is this?' ]
Portland 29
Death Valley 1.6