c++ - 在 C++ 中检查用户输入的正确值

标签 c++ user-input

我有一个接受用户输入值的要求。它可以是整数或字符串。接受用户输入如下。

string strArg;
cout << "Enter price value "  << endl;
std::getline(std::cin, strArg);
int input;
std::stringstream(strArg) >> input;

问题是我如何检查用户输入的是整数而不是字符串,即检查输入是否正确。我们如何在 C++ 中以可移植的方式做到这一点?因为在我的项目中不允许使用 Boost,因为我的经理不喜欢使用它:)

最佳答案

应该这样做:

#include <iostream>
#include <sstream>
#include <string>

int main(void)
{
  std::cout << "input:" << std::endl; 
  std::string input;
  std::getline(std::cin, input);

  std::istringstream str(input);
  int iv = 0;
  // this checks that we've read in an int and we've consumed the entire input, else
  // treat as string.
  if (str >> iv && str.tellg() == input.length())
  {
    std::cout << "int: " << iv << std::endl;
  }
  else
  {
    std::cout << "string: " << input << std::endl;
  }     

  return 0;
}

关于c++ - 在 C++ 中检查用户输入的正确值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5001993/

相关文章:

c++ - 在 std::thread 中打开 MFC 对话框

user-interface - 从用户那里获取日期/时间输入的最佳方法是什么?

c++ - 'int' 的问题

c - 重新分配影响 fgets

javascript - 仅含 mm/yyyy 的 Html 文本框

c++ - 在 C++ 中,对象创建括号前的 Asterisk 是什么意思?

c++ - 奇怪的错误 - 打印出数组的内容会改变结果,即使我从未改变结果

C++ std::queue push pop 两个不同的对象获取第一个对象

c++ - QTableWidget 右键单击​​事件的问题

java - 如何使用 token 拆分用户的输入?