fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <utility>
  5.  
  6. std::istream& Char( std::istream& is,
  7. char ch,
  8. bool skipws = true )
  9. {
  10. if( skipws )
  11. is >> std::ws;
  12. if( is.get() != ch )
  13. is.setstate( std::ios_base::failbit );
  14. return is;
  15. }
  16.  
  17. int main()
  18. {
  19. std::istringstream stream("2x^4-5x^3+3.5x^2+2x-5");
  20.  
  21. using Real = double;
  22.  
  23. std::vector<std::pair<Real, Real>> values;
  24.  
  25. for(;;)
  26. {
  27. Real a, b;
  28.  
  29. if( !(stream >> std::ws >> a) )
  30. break;
  31.  
  32. bool succeeded_x = false;
  33. if( !Char(stream, 'x')
  34. || (succeeded_x = true, !Char(stream, '^')) )
  35. {
  36. stream.clear();
  37. stream.unget();
  38. b = succeeded_x;
  39. }
  40.  
  41. else if( !(stream >> std::ws >> b) )
  42. break;
  43.  
  44. values.emplace_back(a, b);
  45.  
  46. if( stream.peek() != '+'
  47. && stream.peek() != '-' )
  48. break;
  49. }
  50.  
  51. for( auto const& p : values )
  52. std::cout << p.first << " * x^" << p.second << '\n';
  53. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
2 * x^4
-5 * x^3
3.5 * x^2
2 * x^1
-5 * x^0