如何在变量中仅允许数字

How to allow only numbers in a variable?

本文关键字:许数字 数字 变量      更新时间:2023-10-16

我的代码有一些问题,这是我对。

的代码的一部分。

此代码的点是,如果用户输入不是数字的东西,例如字符 p,程序应要求用户再次输入,则此部分有效。

如果用户输入数字和字符程序的组合,则应要求用户再次输入。例如n1212n无效。

部分首先出现字符的部分,例如 n12不会引起问题,但是问题是第一个数字是第一个而其他的,例如 12n,这是无效的,但是我的代码会打印出数字 12及以后说这个数字无效。

#include <iostream>
using namespace std;
int main ()
{
    int n;
    while(1)
    {
        cout<<"Enter a number, 0 for exit: ";
        cin>>n;
        if(!cin)
        {
            cout<<"You didnt enter a valid numbern";
            cin.clear();
            cin.ignore(1000,'n');
            continue;
        }
        cout<<"Number is: "<<n<<endl;
        if(n==0) return 0;
    }
}

代码输出的示例:

Enter a number, 0 for exit: 12
Number is: 12

Enter a number, 0 for exit: n
You didnt enter valid number

Enter a number, 0 for exit: n12
You didnt enter valid number

4°&lt; ----这一个无法正常工作

Enter a number, 0 for exit: 12n
Number is: 12
Enter a number, 0 for exit: You didnt enter valid number

编辑:如果可能的话,我想解决此问题而不包括其他库。

您可以从其他标准库中使用isDigit(),std :: string :: string :: all_of()(可以,不是过分的)在字符串中,然后您检查字符串的每个字符是否成功,这意味着在这种情况下,输入纯粹是数值的):

#include <iostream>
#include <cctype>
#include <string>
int main()
{
    std::string str;
    std::cin >> str;
    (std::all_of(str.begin(), str.end(), [] (char c) { return isdigit(c); })) ? std::cout << "It's a number!n" : std::cout << "isdigit() failedn";
    return 0;
}

输出:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++0x main.cpp 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
4
It's a number!
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
f
isdigit() failed
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
12n
isdigit() failed

您需要检查用户输入的整行,而不仅仅是其中的一部分。istream::operator>>遇到不属于当前正在读取的数据类型的字符时停止阅读。这就是为什么像12n这样的输入分别以12n的处理。

您不会仅使用<iostream>功能来解决此问题。最好使用std::getline()std::stoi()/std::strtol()(例如:

)来处理这
#include <iostream>
#include <string>
using namespace std;
bool to_int(const string &str, int &i)
{
    size_t pos;
    i = stoi(str, &pos);
    return (str.c_str()[pos] == '');
}
int main ()
{
    string line;
    int n;
    do
    {
        cout << "Enter a number, 0 for exit: ";
        getline(cin, line);
        if (!to_int(line, n))
        {
            cout << "You didn't enter a valid numbern";
            continue;
        }
        cout << "Number is: " << n << endl;
        if (n == 0) break;
    }
    while (1);
    return 0;
}

如果您不想使用std::stoi()这样的转换功能,则至少使用std::istringstream

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
bool to_int(const string &str, int &i)
{
    char c;
    istringstream iss(str);
    iss >> i;
    return !(iss.fail() || iss.get(c));
}
int main ()
{
    string line;
    int n;
    do
    {
        cout << "Enter a number, 0 for exit: ";
        getline(cin, line);
        if (!to_int(line, n))
        {
            cout << "You didn't enter a valid numbern";
            continue;
        }
        cout << "Number is: " << n << endl;
        if (n == 0) break;
    }
    while (1);
    return 0;
}

循环通过数字,如果它具有数字以外的其他内容,请打印"您没有输入有效的数字",否则打印数字。我们将作为字符串输入并使用ctype.h验证字符串的字符是否是数字:

#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
int main()
{
    string n;
    bool is_valid = true;
    while (1)
    {
        cout << "Enter a number, 0 for exit: ";
        cin >> n;
        for (size_t i = 0; i < n.length(); i++) {
            if (!isdigit(n[i])) {
                cout << "You didnt enter a valid numbern";
                is_valid = false;
                break;
            }
        }
        if (is_valid) cout << "Number is: " << n << endl;
        if (n == "0") return 0;
    }
}