所以我希望能够使除特定单词(如 'K'
或 'C'
之外的所有用户输入无效。我完全不确定该怎么做。因此,如果他们将其拼错为“celcius”或“husdhfjae”,我的程序会说 “Input invalid, please enter K or C.”
请不要太复杂,因为我才刚刚开始。谢谢 :)
// CS 575,HW #1B, Ravela Smyth
// This program converts from Fahrenheit to Celsius or Kelvin
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
double Fahrenheit, celsius, kelvin;
cout << "Hi! What is the weather today in Fahrenheit?? " << endl;
cin >> Fahrenheit;
cout << "Would you like to convert this temperature to Celsius or Kelvin? (C/K)" << endl;
cin >> input;
if (input == "C")
{
celsius = (5 * (Fahrenheit - 32)) / 9;
cout << "Today's weather in Celsius is " << celsius << " degrees! " << endl;
}
else if (input == "c")
{
celsius = (5 * (Fahrenheit - 32)) / 9;
cout << "Today's weather in Celsius is " << celsius << " degrees! " << endl;
}
else if (input == "K")
{
kelvin = (5 * (Fahrenheit + 459.67)) / 9;
cout << "Today's weather in Kelvin is " << kelvin << " degrees!" << endl;
}
else if (input == "k")
{
kelvin = (5 * (Fahrenheit + 459.67)) / 9;
cout << "Today's weather in Kelvin is " << kelvin << " degrees!" << endl;
}
return 0;
}
最佳答案
通常使用while
或do...while
循环检查用户输入。
这个想法很简单,您总是会返回到相同的错误消息并再次读取输入,直到它正确为止。
将有效选项放在单个 string
中的优点是允许轻松添加或删除选项,而无需处理长的 if
条件。
我相信像这样简单的事情就能完成这项工作:
std::string valid_options("kKcC");
std::string input;
bool illegal_input;
std::cout << "Would you like to convert this temperature to Celsius or Kelvin? (C/K)" << std::endl;
std::cin >> input;
// check that only one letter was provided and it belongs to the valid options
while (input.size() != 1 || valid_options.find(input) == std::string::npos)
{
std::cout << "Input invalid, please enter K or C.\n";
std::cin >> input;
}
关于c++ - 如何检查用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32426598/