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

Checking cin input stream produces an integer

本文关键字:一个 整数 cin 输入流 检查      更新时间:2023-10-16

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

如何让计算机检查输入的内容是否为整数?如果没有,请让用户键入一个整数。 例如:如果有人输入"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;
}

你可以这样检查:

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;
}

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

用户输入应以字符串形式获取,然后尝试转换为所需的数据类型。方便的是,这也允许您回答诸如"我的输入是什么类型的数据?

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

template <typename T>
auto string_to( const std::string & s )
{
  T value;
  std::istringstream ss( s );
  return ((ss >> value) and (ss >> std::ws).eof())  // attempt the conversion
    ? value                                         // success
    : std::optional<T> { };                         // 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

c中有一个函数叫做isdigit()。那会适合你。例:

int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
   printf("var1 = |%c| is a digitn", var1 );
}
else
{
   printf("var1 = |%c| is not a digitn", var1 );
}
if( isdigit(var2) )
{
  printf("var2 = |%c| is a digitn", var2 );
}
else
{
   printf("var2 = |%c| is not a digitn", var2 );
}

从这里

如果 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

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

#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[ERRORtINVALID INPUT]n"; 
    return 1; 
} 
return 0;    
}

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

#include #include <限制>//std::numeric_limits使用 std::cout, std::endl, std::cin;int main() {    整数;    而(!(cin>> num)){//以正确的方式检查整数的输入格式        cin.clear();        cin.ignore(std::numeric_limits<std::streamsize>::max(), '');        cout <<"输入无效。 重新输入数字:";      };    cout <<"output= " <<num <<endl;    返回 0;}

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

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

此方法失败的唯一情况是输入中的数字后面有尾随空格,即用户在输入数字后输入大量空格。要处理这种情况,您可以按照本文中所述修剪输入字符串。

#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;
}

您可以使用:

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

我很确定它有效。

相关文章: