fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4.  
  5. std::istream& get_word_or_quote( std::istream& is, std::string& s )
  6. {
  7. char c;
  8.  
  9. // skip ws and get the first character
  10. if ( !std::ws( is ) || !is.get( c ) )
  11. return is;
  12.  
  13. // if it is a word
  14. if ( c != '"' )
  15. {
  16. is.putback( c );
  17. return is >> s;
  18. }
  19.  
  20. // if it is a quote (no escape sequence)
  21. std::string q;
  22. while ( is.get( c ) && c != '"' )
  23. q += c;
  24. if ( c != '"' )
  25. throw "closing quote expected";
  26.  
  27. //
  28. s = std::move( q );
  29. return is;
  30. }
  31.  
  32. int main()
  33. {
  34. std::istringstream is {"not-quoted \"quoted\" \"quoted with spaces\" \"no closing quote!" };
  35.  
  36. try
  37. {
  38. std::string word;
  39. while ( get_word_or_quote( is, word ) )
  40. std::cout << word << std::endl;
  41. }
  42. catch ( const char* e )
  43. {
  44. std::cout << "ERROR: " << e;
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 16056KB
stdin
Standard input is empty
stdout
not-quoted
quoted
quoted with spaces
ERROR: closing quote expected