簡體   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