如何检查输入是否是没有任何其他字符的有效整数

How to check if the input is a valid integer without any other chars?

本文关键字:其他 任何 字符 整数 有效 是否是 何检查 检查 输入      更新时间:2023-10-16
#include <iostream>
#include <limits>
using namespace std;
int main()
{
    int x;
    cout << "5 + 4 = ";
    while(!(cin >> x)){
        cout << "Error, please try again." << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
    }
    if (x == (5 + 4)){
        cout << "Correct!" << endl;
    }
    else{
        cout << "Wrong!" << endl;
    }
    return 0;
}

如何检查用户输入的整数是否有效?在我上面写的这个程序中,如果用户输入9,它应该是正确的,但是,如果用户输入9a例如,它应该返回错误,但由于某种原因没有。我该如何纠正它?

我如何使用cin.peek((做到这一点

#include <iostream>
#include <limits>
#include <stdio.h>
using namespace std;
int main()
{
    int x;
    bool ok;
    cout << "5 + 4 = ";
    cin >> x;
    while(!ok){
  cin >> x;
  if(!cin.fail() && (cin.peek() == EOF || cin.peek() == 'n')){
  ok = true;
  }
  else{
  cout << "Error, please try again." << endl;
  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(), 'n');
  }
    }
    if (x == (5 + 4)){
  cout << "Correct!" << endl;
    }
    else{
  cout << "Wrong!" << endl;
    }
    return 0;
}

你可以读取一个字符串,从中提取一个整数,然后确保没有剩余的东西:

std::string line;
std::cin >> line;
std::istringstream s(line);
int x;
if (!(s >> x)) {
  // Error, not a number
}
char c;
if (s >> c) {
  // Error, there was something past the number
}
bool isIntegerNumber(const std::string& string){
  std::string::const_iterator it = string.begin();
  int minSize = 0;
  if(string.size()>0 && (string[0] == '-' || string[0] == '+')){
    it++;
    minSize++;
  }
  while (it != string.end() && std::isdigit(*it)) ++it;
  return string.size()>minSize && it == string.end();
}

您有一个面向行的输入,因此您可能应该使用 getline . 像这样:

bool
getIntFromLine( std::istream& source, int& results )
{
    std::string line;
    std::getline( source, line );
    std::istringstream parse( source ? line : "" );
    return parse >> results >> std::ws && parse.get() == EOF;
}

应该做这个伎俩。

使用它,您的循环将是:

while ( !getIntFromLine( std::istream, x ) ) {
    std::cout << "Error, please try again." << std::endl;
}

请注意,此技术也意味着您不必担心关于清除错误或重新同步输入。

有关发生这种情况的原因,请查看此链接:

顺序从流中提取字符并将其解析为 将它们解释为正确类型的值的表示形式, 存储为 val 的值。在内部,函数访问 通过首先构造哨兵对象(使用 noskipws 设置为 false(。然后(如果好的话(,它调用num_get::get(使用 流的选定区域设置(来执行提取和 解析操作,调整流的内部状态标志 因此。最后,它在返回之前摧毁了哨兵物体。

然后,如果您尝试执行以下操作,请观察该行为:

int x = 0;
cin >> x;
std::cout << x << std::endl;
std::cout << cin.good() << std::endl;
g++-4.8 -std=c++11 -O3 -Wall -pedantic -pthread main.cpp && echo "900a100" | ./a.out
// Output:
// 900
// 1

如果改为输入"a100",它将输出:

0
0

试试这个:

std::string input;
std::cin >> input;
if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
     //input is integer
}

参考这个 :

C++ 修复了检查输入是否为整数的问题

我看到的适用于某些情况的一种是:

  • 将输入读取为字符串。 cin >> str
  • 解码为数字:atoi,或sscanf,或stringstream等。
  • 将数字打印成字符串(使用 Sprintf 或字符串流(
  • 检查它是否等于读取字符串。(使用字符串 ==,而不是字符*(

快速简单。 使用 Cin>>str 断字规则,接受负数,拒绝溢出的数字。但它确实拒绝"+10",在某些情况下你很满意,而在某些情况下你不满意。

如果你可以使用 C++11(并且你的编译器有完整的正则表达式支持(,你也可以使用 <regex> 库:

#include <iostream>
#include <limits>
#include <regex>
#include <string>
#include <utility>
int main()
{
    std::string line;
    std::pair<int, bool> value = std::make_pair(0, false);
    std::cout << "5 + 4 = ";
    while (!value.second)
    {
        while (!std::getline(std::cin, line))
        {
            std::cout << "Error, please try again." << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        }
        if (!std::regex_match(line, std::regex("(\+|-)?[[:digit:]]+")))
        {
            std::cout << "Error, please try again." << std::endl;
        }
        else
        {
            value = std::make_pair(std::stol(line), true);
        }
    }
    if (value.first == (5 + 4))
    {
        std::cout << "Correct!" << std::endl;
    }
    else
    {
        std::cout << "Incorrect!" << std::endl;
    }
    return 0;
}
相关文章: