问题
In a C++ program I'm trying to process user input which consists of integer operands interspersed with operators (+ - / *). I have the luxury of requiring users to put whitespace(s) before and after each operator. My approach is to assume that anything that's not an int is an operator. So as soon as there's a non eof error on the stream, I call cin.clear() and read the next value into a string.
#include <iostream>
#include <string>
//in some other .cpp i have these functions defined
void process_operand(int);
void process_operator(string);
using namespace std;
int main()
{
int oprnd;
string oprtr;
for (;; )
{
while ( cin >> oprnd)
process_operand(oprnd);
if (cin.eof())
break;
cin.clear();
cin >> oprtr;
process_operator(oprtr);
}
}
This works fine for / and * operators but not for + - operators. The reason is that operator>>
eats away the + or - before reporting the error and doesn't put it back on the stream. So I get an invalid token read into oprtr.
Ex: 5 1 * 2 4 6 * / works fine
5 1 + 2
^ ---> 2 becomes the oprnd here.
What would be a good C++ way of dealing with this problem?
回答1:
Read in std::string
s and convert them using boost::lexical_cast<> or its equivalent.
int main()
{
string token;
while ( cin >> token) {
try {
process_operand(boost::lexical_cast<int>(token));
} catch (std::bad_cast& e) {
process_operator(token);
}
}
}
Postscript: If you are allergic to Boost, you can use this implementation of lexical_cast:
template <class T, class U>
T lexical_cast(const U& u) {
T t;
std::stringstream s;
s << u;
s >> t;
if( !s )
throw std::bad_cast();
if( s.get() != std::stringstream::traits_type::eof() )
throw std::bad_cast();
return t;
}
回答2:
I think >> thinks you are starting another integer with +/-. Then gets mad when you don't follow with digits.
As @Robᵩ said, read a string and cast. I would only offer another choice from the standard library:
int stoi(const string& str, size_t *idx = 0, int base = 10);
This throws invalid_argument
if no conversion could be performed or out_of_range
if the converted value is outside the range of representable values for the return type.
This is from The Standard.
来源:https://stackoverflow.com/questions/10586720/cin-i-error-in-input-with-symbol