繁体   English   中英

C ++-清除整数输入

[英]C++ - Sanitize Integer Whole Number Input

我当前正在使用在另一个StackOverflow帖子中找到的函数(我找不到它),该函数以前使用的名为“ GetInt”。 我的问题是,如果用户输入类似“ 2 2 2”的内容,则会将其放入我的下两个Cin中。 我已经尝试过getLine,但是它需要一个字符串,并且我正在寻找一个int值。 我将如何构造检查以清除大于2的整数值并向2 2 2答案抛出错误。

#include <iostream>
#include <string>
#include <sstream>
#include "Board.cpp"
#include "Player.cpp"

using namespace std;

int getInt()
{
int x = 0;
while (!( cin >> x))
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Please input a proper 'whole' number: " << endl;
}
return (x);
}

和我的电话

do
{
    //do
    //{
        cout << "How many players are there? \n";
        numberOfPlayers = getInt();
    //} while (isdigit(numberOfPlayers) == false);
} while (numberOfPlayers < 2);

编辑:

我选择Justin的答案是因为它与我的原始代码最接近,因此无需进行重大更改即可解决该问题。

整数由空格分隔,输入2 2 2只是多个整数。 如果要确保每行只输入一个整数,则可以跳过空格字符,直到找到换行符为止。 如果在换行符之前找到非空格,则可能会发出错误:

numberOfPlayers = getInt();
int c;
while (std::isspace(c = std::cin.peek()) && c != '\n') {
    std::cin.ignore();
}
if (c != std::char_traits<char>::eof() && c != '\n') {
    // deal with additional input on the same line here
}

您使用std::getline在正确的轨道上。 您将整个行作为字符串读取,然后将其放入std::istringstream并读取整数。

std::string line;
if( std::getline(cin, line) ) {
    std::istringstream iss(line);
    int x;
    if( iss >> x ) return x;
}
// Error

这将具有丢弃整数之后出现的任何绒毛的效果。 仅当没有输入或无法读取整数时才会出错。

如果您希望在整数后面出现填充时出错,则可以利用从流中读取字符串的方式。 任何空格都可以,但是其他任何东西都是错误:

    std::istringstream iss(line);
    int x;
    if( iss >> x ) {
        std::string fluff;
        if( iss >> fluff ) {
            // Error
        } else {
            return x;
        }
    }

将代码更改为此:

int getInt()
{
    int x = 0;
    while (!( cin >> x))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        cout << "Please input a proper 'whole' number: " << endl;
     }

     cin.clear();
     cin.ignore(numeric_limits<streamsize>::max(), '\n');
     return (x);
 }

仅当整数收集失败时(例如,您键入“ h”作为播放器的数目),才调用您的代码以忽略接收整数后的其余行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM