c++只接受数值

C++ cin only accept numeric values

本文关键字:c++      更新时间:2023-10-16

我编写了这段代码,允许用户选择输入值1或2。除了一个小问题之外,这工作得非常好:

如果用户输入类似"1asdaosd"的内容,则输入只被识别为1。

我已经尝试使用isdigit函数,但我仍然没有设法使这个工作。

bool validInput;
    do
    {
        cout << "Choose the game type: ";
        cin >> gametype;
        validInput = true;
        if (cin.fail())
        {
            validInput = false;
            cin.clear();
            cin.ignore(std::numeric_limits<int>::max(), 'n');
        }
        if (gametype<1 || gametype>2) {
            validInput = false;
        }
    } while (!validInput);

The expected behaviour should be:

Anything other than "1" or "2" shouldn't be considered a validInput and therefore repeating the cycle. What happens is that "1asdasd" or "2aods" is considered a validInput but I want it to fail.

Below is a method based on stuff I read in one of the early chapters of Stroustrup's Programming: Principles and Practice Using C++ and an answer provided by Duoas at cplusplus.com. It defines a function, get_int_between(), that allows you to do something like this:

int my_variable;
get_int_between(my_variable, min, max, prompt, error_msg);

将提示、验证并存储到my_variable中。

只是为了好玩,我还包含了一个函数get_int(my_variable, prompt, error_msg),它做同样的事情,但允许任何值的整数。

#include <iostream>
#include <sstream> // stringstream
void get_int(int& d, std::string prompt, std::string fail);
void get_int_between(int& d, int min, int max, std::string prompt, std::string fail);
int main()
{
    int my_number = 1; // initialize my_number
    get_int(my_number, "Please enter an integer: ", "Sorry, that's not an integer.n"); 
    //Do something, e.g. 
    std::cout << "You entered: " << my_number << "n";
    get_int_between(my_number, 1, 2, "Choose the game type (1 or 2): ", "Sorry, that's not an integer.n");
    //Do something, e.g.:
    std::cout << "Let's play Game " << my_number << "!n";
    return 0;
}
void get_int(int& d, std::string prompt, std::string fail)
{
    while(1) {
        std::cout << prompt;
        std::string str;
        std::cin >> str;
        std::istringstream ss(str);
        int val1;
        ss >> val1;
        if(!ss.eof()) {
            std::cout << fail;
            continue;
        } else {
            d = val1;
            break;
        }
    }
}
void get_int_between(int& d, int min, int max, std::string prompt, std::string fail)
{
    while(1) {
        get_int(d, prompt, fail);
        if(d > max || d < min) {
            std::cout << "Sorry, your choice is out of range.n";
            continue;
        }
        break;
    }
}

如果您想使用字符串,请使用getline。

#include <iostream>     // std::cin, std::cout
int main () 
{
char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);
std::cout << name << "'s favourite movie is " << title;
return 0;
}

如果你将gametype设置为int,它将只接受1或2(当然你必须阻止其他数字被接受)。

这是因为gametype是一个整数,所以它试图读取尽可能多的整数有效。1asdaosd不是一个有效的整数,所以它在1处停止。例如,如果你想完全读取它,你必须将gametype设置为字符串,但这样你就不能像之前那样将其与整数进行比较了。

如果你想的话,你可以把它读成字符串,如果你想处理字符串和整型的情况,那么你可以使用stoi之类的东西来尝试把字符串转换成整数。然后捕获std::invalid_argument异常,这样您就可以知道字符串是否可以转换为整数。

只要输入可以解释为int,它就读取int。然后停止。如果你读入一个字符串变量,它将得到它的全部

  1. 将数据读取到字符串变量中。
  2. 检查数据是否为有效整数
  3. 将字符串转换为整数。

很乏味,但这是唯一的方法

我猜您希望每行都有一个输入值。你需要把它读成字符串,然后检查你得到的是否比你要求的多。如果您需要将其转换为整数,则可以稍后转换读字符串。

我还假设您只需要读取个位数整数。更多的数字需要在循环中将字符串转换为整数,并进行更多的检查。

string gametype;
do
{
    cout << "Choose the game type: ";
    // read one word as string, no conversion, so will not fail (may hit eof though)
    cin >> gametype;
    // ignore rest of line (assuming you want next valid input on next line)
    cin.ignore(std::numeric_limits<int>::max(), 'n');
}
while ( gametype.size() != 1 || gametype.at(0) < '1' || gametype.at(0) > '2') );
// char to int conversion (single digit only)
int gametypeint = gametype.at(0) - '0';
// other way to convert string to int
istringstream iss(gametype);
iss >> gametypeint;
// yet another way (C++11)
gametypeint = stio(gametype);
相关文章:
  • 没有找到相关文章