如何处理这种副作用
How to deal with this side effect?
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;
如何更改代码以使+32423
对cin
不正确?
您需要准确确定您需要从用户那里获得的输入是什么以及是什么使其有效。在我看来,这听起来像您想接受来自用户的整行输入(因此您应该将std::getline
与std::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
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用流处理接收到的数据
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 基于多个条件处理地图中的所有元素
- 如何用数字处理log(0)
- SSL上的`curl_easy_send`和`curl_asy_recv`:如何处理`CURLE_AGAIN`
- 错误处理.将系统错误代码映射到泛型
- 从文本文件中读取时钟时间和事件时间并进行处理
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 用于矢量处理的多个线程
- 对字符串进行排序时,在c++中处理sort()
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- 处理除以零会导致<csignal>意外行为
- 是否可以在c++中处理字符串流中的各个元素
- 如何处理这种副作用