Question

char sign;
cout << "Enter '+' for addition or '-' for subtraction: ";
cin >> sign;
if ( sign != '+' && sign != '-' ) {
     cout << "you can only enter '+' or '-'!\n";
     return 1;
}

If I enter +32423, the input is still correct to the cin(it will pass the checking), because + will be automatically set to sign variable, and also 32423 will be stored into my next variable if there is:

cin >> number;

How can I change the code so that +32423 is incorrect to the cin?

Was it helpful?

Solution

You need to decide exactly what the input you require from the user is and what makes it valid. It sounds to me like you want to accept an entire line of input from the user (so you should use std::getline with a std::string) and then you want to only accept strings that are exactly "+" and "-".

std::string sign;
std::getline(std::cin, sign); // Gather input
if (sign != "+" && sign != "-") { // Parse input
  // ...
}
// ...

As @H2C03 mentioned, it's a good idea to split up the inputting and the parsing. In this case, the parsing is as simple as comparing the input line to the strings "+" and "-".

OTHER TIPS

Don't try to do two things in one step. This is a common error -- don't feel too bad, the designers of the scanf() family of funcionts and std::istream::operator>> made the exact same mistake.

What you are trying to do: get user input and parse it in order to perform a computation.

What you are actually doing: you are doing these inhrenetly different things in one step, and this is making you confused. You should clearly and cleanly separate the two steps instead: first, get the user input, and the parse it properly. As in:

// get an entire line
std::string line;
std::getline(std::cin, line);

// parse it: only the format <some digits> <'+' or '-'> <other digits>
// is acceptable, most probably with interspersed whitespace
std::string::iterator it = line.begin();
while (isspace(*it) && it != line.end())
    it++;

std::string::iterator it2 = it;
while (isdigit(*it) && it != line.end())
    it++;

std::string first_number(it2, it); // construct a new substring for the 1st number

// etc. continue the parsing in a similar manner
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top