Output error when input isn't a number. C++

前端 未结 5 1852
野性不改
野性不改 2021-01-28 07:47

I am making a function that takes a number from the user\'s input and finds the absolute value of it. I want to make it return an error if the user inputs anything other than j

5条回答
  •  伪装坚强ぢ
    2021-01-28 08:26

    In addition to the great answers here, you could try using std::stringstream:

    http://cplusplus.com/reference/iostream/stringstream/stringstream/

    It works like any other stream for the most part, so you could do something like:

      int converted;
      string user_input;
    
      cin >> user_input;
    
      stringstream converter(user_input);
    
    
      if(!(converter >> converted)) {
        cout << "there was a problem converting the input." << endl;
      }
      else {
        cout << "input successfully converted: " << converted << endl;
      }
    

    HTH!

    P.S. personally, I would just use boost::lexical_cast<>, but for a homework assignment you probably won't have boost available to you. If you become a professional C++ programmer, Boost will become one of your best friends outside of the STL.

提交回复
热议问题