c++ - 如何检查用户输入?

标签 c++

所以我希望能够使除特定单词(如 '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;
}

最佳答案

通常使用whiledo...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/

相关文章:

c++ - 从 iostream 读取父类(super class)的子类实例。 >> 运算符如何知道哪个子类?

c++ - 将 QSpinBox 添加到 QTreeWidgetItem 的子项

c++ - 代码块中的歧义编译

容器在使用前销毁/修改时的 C++ 警告(通过引用元素或迭代器使用)

c++ - 错误 : opencv2/core/core. hpp:没有那个文件或目录

c++ - 如何在处理 Windows 事件时保持 Qt Widgets 对键盘和鼠标的响应?

c++ - 未调用 boost SSL async_shutdown 完成处理程序

c++ - 在一个类上重载 ostream << 并输出另一个类的数据

C++:字符串 vector 的随机访问时间如何工作?

c++ - 应用程序中的运行时错误 - 分段失败