fork(2) download
  1. #include <string>
  2. #include <sstream>
  3. #include <iostream>
  4.  
  5. int main()
  6. {
  7. // open the stream which contains the city data
  8. // (this example uses a stringstream instead of a filestream)
  9. std::istringstream stm( R"(
  10. A|City1|Data.1|Data.2|Data.3
  11. R|01R|Data.4|Data.5|Data.6
  12. R|02R|Data.4|Data.5|Data.6
  13. R|03R|Data.4|Data.5|Data.6
  14. R|04R|Data.4|Data.5|Data.6
  15.  
  16. A|City2|Data..1|Data..2|Data..3
  17. R|01R|Data..4|Data..5|Data..6
  18. R|02R|Data..4|Data..5|Data..6
  19. R|03R|Data..4|Data..5|Data..6
  20. R|04R|Data..4|Data..5|Data..6
  21.  
  22. A|City3|Data...1|Data...2|Data...3
  23. R|01R|Data...4|Data...5|Data...6
  24. R|02R|Data...4|Data...5|Data...6
  25. R|03R|Data...4|Data...5|Data...6
  26. R|04R|Data...4|Data...5|Data...6
  27.  
  28. )" ) ;
  29.  
  30. // get the city name
  31. std::string city_name = "City2" ;
  32.  
  33. // we need to look a line starting with
  34. // the city_name prefixed by "A|" and suffixed by '|'
  35. const std::string search_string = "A|" + city_name + '|' ;
  36.  
  37. // read and discard lines from the stream
  38. // till we get to a line starting with the search_string
  39. std::string line ;
  40. while( std::getline( stm, line ) && line.find(search_string) != 0 ) ;
  41.  
  42. // check if we have found such a line, if not report an error
  43. if( line.find(search_string) != 0 )
  44. {
  45. std::cerr << "city '" << city_name << " was not found\n" ;
  46. return 1 ;
  47. }
  48.  
  49. // we need to form a string that would include the whole set of data
  50. // based on the selection of City
  51. std::string result = line + '\n' ; // result initially contains the first line
  52.  
  53. // now keep reading line by line till we get an empty line or eof
  54. while( std::getline( stm, line ) && !line.empty() )
  55. result += line + '\n' ; // append this line to the result
  56.  
  57. // use the result (in this example, we just print it out)
  58. std::cout << "data for '" << city_name << "'\n--------------\n" << result ;
  59. }
  60.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
data for 'City2'
--------------
A|City2|Data..1|Data..2|Data..3
R|01R|Data..4|Data..5|Data..6
R|02R|Data..4|Data..5|Data..6
R|03R|Data..4|Data..5|Data..6
R|04R|Data..4|Data..5|Data..6