如何处理这种副作用

How to deal with this side effect?

本文关键字:副作用 处理 何处理      更新时间:2023-10-16
char sign;
cout << "Enter '+' for addition or '-' for subtraction: ";
cin >> sign;
if ( sign != '+' && sign != '-' ) {
     cout << "you can only enter '+' or '-'!n";
     return 1;
}

如果我输入 +32423 ,输入对cin仍然正确(它将通过检查),因为+将自动设置为符号变量,并且如果有,32423将被存储到我的下一个变量中:

cin >> number;

如何更改代码以使+32423cin不正确?

您需要准确确定您需要从用户那里获得的输入是什么以及是什么使其有效。在我看来,这听起来像您想接受来自用户的整行输入(因此您应该将std::getlinestd::string一起使用),然后您只想接受完全"+""-"的字符串。

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

正如@H2C03提到的,将输入和解析分开是个好主意。在这种情况下,解析就像将输入行与字符串进行比较一样简单 "+""-" .

不要试图一步到位地做两件事。这是一个常见的错误 - 不要觉得太糟糕,scanf()系列功能的设计者和std::istream::operator>>犯了完全相同的错误。

您要做的是:获取用户输入并解析它以执行计算。

實際上在做什麼:你一步到位地做這些截然不同的事情,這讓你感到困惑。您应该清晰明了地将两个步骤分开:首先,获取用户输入,并正确解析它。如:

// 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