检查cin输入流会产生一个整数

时间:2013-09-10 21:06:12

标签: c++ cin

我输入了这个,它要求用户输入两个整数然后变成变量。从那里它将执行简单的操作。

如何让计算机检查输入的内容是否为整数?如果没有,请让用户键入一个整数。例如:如果有人输入“a”而不是2,那么它会告诉他们重新输入一个数字。

由于

 #include <iostream>
using namespace std;

int main ()
{

    int firstvariable;
    int secondvariable;
    float float1;
    float float2;

    cout << "Please enter two integers and then press Enter:" << endl;
    cin >> firstvariable;
    cin >> secondvariable;

    cout << "Time for some simple mathematical operations:\n" << endl;

    cout << "The sum:\n " << firstvariable << "+" << secondvariable 
        <<"="<< firstvariable + secondvariable << "\n " << endl;

}

8 个答案:

答案 0 :(得分:25)

您可以这样检查:

int x;
cin >> x;

if (cin.fail()) {
    //Not an int.
}

此外,您可以继续获取输入,直到获得int:

#include <iostream>



int main() {

    int x;
    std::cin >> x;
    while(std::cin.fail()) {
        std::cout << "Error" << std::endl;
        std::cin.clear();
        std::cin.ignore(256,'\n');
        std::cin >> x;
    }
    std::cout << x << std::endl;

    return 0;
}

编辑:要解决以下关于10abc等输入的注释,可以修改循环以接受字符串作为输入。然后检查字符串中是否有任何字符而不是数字并相应地处理该情况。在那种情况下,人们不需要清除/忽略输入流。验证字符串只是数字,将字符串转换回整数。我的意思是,这只是袖口。可能有更好的方法。如果你接受浮点数/双打(不得不在搜索字符串中添加'。'),这将无效。

#include <iostream>
#include <string>

int main() {

    std::string theInput;
    int inputAsInt;

    std::getline(std::cin, theInput);

    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

        std::cout << "Error" << std::endl;

        if( theInput.find_first_not_of("0123456789") == std::string::npos) {
            std::cin.clear();
            std::cin.ignore(256,'\n');
        }

        std::getline(std::cin, theInput);
    }

    std::string::size_type st;
    inputAsInt = std::stoi(theInput,&st);
    std::cout << inputAsInt << std::endl;
    return 0;
}

答案 1 :(得分:1)

c中有一个名为isdigit()的函数。这很适合你。例如:

int var1 = 'h';
int var2 = '2';

if( isdigit(var1) )
{
   printf("var1 = |%c| is a digit\n", var1 );
}
else
{
   printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
  printf("var2 = |%c| is a digit\n", var2 );
}
else
{
   printf("var2 = |%c| is not a digit\n", var2 );
}

来自here

答案 2 :(得分:1)

如果istream无法插入,则会设置失败位。

int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
    std::cout << "I failed, try again ..." << std::endl
    std::cin.clear(); // reset the failed state
}

您可以在do-while循环中进行设置,以获得正确插入的正确类型(在这种情况下为int)。

有关详细信息:http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly

答案 3 :(得分:1)

嘿,这是一个老问题,可以使用更好的答案。

用户输入应以字符串获取,然后尝试转换获取所需的数据类型。方便的是,这也允许您回答“我的输入是什么类型的数据?”等问题。

这是我经常使用的一个功能。存在其他选项,例如在Boost中,但基本前提是相同的:尝试执行字符串→类型转换并观察成功或失败:

template <typename T>
std::optional <T> string_to( const std::string& s )
{
  std::istringstream ss( s );
  T result;
  ss >> result >> std::ws;      // attempt the conversion
  if (ss.eof()) return result;  // success
  return {};                    // failure
}

使用optional类型只是一种方式。您还可以抛出异常或在失败时返回默认值。什么适合你的情况。

以下是使用它的示例:

int n;
std::cout << "n? ";
{
  std::string s;
  getline( std::cin, s );
  auto x = string_to <int> ( s );
  if (!x) return complain();
  n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";

限制和类型识别

当然,为了实现这一点,必须存在一种从流中明确提取数据类型的方法。这是C ++中事物的自然顺序 - 也就是说,照常运行。所以这里没什么惊喜。

下一个警告是某些类型包含其他类型。例如,如果您要尝试区分intdouble,请首先检查int,因为转换为int的任何内容也是double

答案 4 :(得分:0)

您可以使用变量名称本身来检查值是否为整数。 例如:

#include <iostream>
using namespace std;

int main (){

int firstvariable;
int secondvariable;
float float1;
float float2;

cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;

if(firstvariable && secondvariable){
    cout << "Time for some simple mathematical operations:\n" << endl;

    cout << "The sum:\n " << firstvariable << "+" << secondvariable 
    <<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
    cout << "\n[ERROR\tINVALID INPUT]\n"; 
    return 1; 
} 
return 0;    
}

答案 5 :(得分:0)

我更喜欢使用<limits>来检查int,直到通过为止。

#include <iostream>
#include <limits> //std::numeric_limits

using std::cout, std::endl, std::cin;

int main() {
    int num;
    while(!(cin >> num)){  //check the Input format for integer the right way
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Invalid input.  Reenter the number: ";
      };

    cout << "output= " << num << endl;

    return 0;
}

答案 6 :(得分:0)

在 C++11 及更高版本下,我发现 std::stoi 函数对这项任务非常有用。如果无法执行转换,stoi 将抛出 invalid_argument 异常。这可以按照下面的演示函数“getIntegerValue”所示进行捕获和处理。

stoi 函数有第二个参数 'idx' 表示字符串中数字后第一个字符的位置。我们可以使用 idx 中的值来检查字符串长度并确定输入中是否有除数字以外的任何字符。这有助于消除诸如 10abc 或十进制值之类的输入。

这种方法唯一失败的情况是输入中数字后面有尾随空格,即用户输入数字后输入了很多空格。要处理这种情况,您可以按照 this post 中的描述对输入字符串进行 rtrim。

#include <iostream>
#include <string>

bool getIntegerValue(int &value);

int main(){
    
    int value{};
    bool valid{};

    while(!valid){
        std::cout << "Enter integer value: ";
        valid = getIntegerValue(value);
        if (!valid)
            std::cout << "Invalid integer value! Please try again.\n" << std::endl;
    }
    
    std::cout << "You entered: " << value << std::endl;

    return 0;
}

// Returns true if integer is read from standard input
bool getIntegerValue(int &value){
    bool isInputValid{};
    int valueFromString{};
    size_t index{};
    
    std::string userInput;
    std::getline(std::cin, userInput);

    try {
        //stoi throws an invalid_argument exception if userInput cannot be
        //converted to an integer.
        valueFromString = std::stoi(userInput, &index);

        //index being different than length of string implies additional
        //characters in input that could not be converted to an integer.
        //This is to handle inputs like 10str or decimal values like 10.12
        if(index == userInput.length()) isInputValid = true;
    }
    catch (const std::invalid_argument &arg) {
        ;       //you could show an invalid argument message here.
    }

    if (isInputValid) value = valueFromString;

    return isInputValid;
}

答案 7 :(得分:-2)

您可以使用:

int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}

我很确定它有效。

相关问题