亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查cin輸入流產生一個整數

檢查cin輸入流產生一個整數

C++
交互式愛情 2019-10-11 13:57:11
我正在鍵入它,它要求用戶輸入兩個整數,然后將它們變成變量。從那里將執行簡單的操作。如何讓計算機檢查輸入的內容是否為整數?如果不是,則要求用戶輸入一個整數。例如:如果有人輸入“ a”而不是2,它將告訴他們重新輸入數字。謝謝 #include <iostream>using namespace std;int main (){    int firstvariable;    int secondvariable;    float float1;    float float2;    cout << "Please enter two integers and then press Enter:" << endl;    cin >> firstvariable;    cin >> secondvariable;    cout << "Time for some simple mathematical operations:\n" << endl;    cout << "The sum:\n " << firstvariable << "+" << secondvariable         <<"="<< firstvariable + secondvariable << "\n " << endl;}
查看完整描述

3 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

您可以像這樣檢查:


int x;

cin >> x;


if (cin.fail()) {

    //Not an int.

}

此外,您可以繼續獲取輸入,直到通過以下方式獲取整數為止:


#include <iostream>




int main() {


    int x;

    std::cin >> x;

    while(std::cin.fail()) {

        std::cout << "Error" << std::endl;

        std::cin.clear();

        std::cin.ignore(256,'\n');

        std::cin >> x;

    }

    std::cout << x << std::endl;


    return 0;

}

編輯:要解決以下有關10abc之類的輸入的注釋,可以修改循環以接受字符串作為輸入。然后檢查字符串中是否包含數字以外的任何字符,并相應地處理該情況。在那種情況下,不需要清除/忽略輸入流。驗證字符串只是數字,然后將字符串轉換回整數。我的意思是,這只是袖手旁觀。可能有更好的方法。如果您接受浮點數/雙精度數,則此方法將無效(必須在搜索字符串中添加“?!保?/p>


#include <iostream>

#include <string>


int main() {


    std::string theInput;

    int inputAsInt;


    std::getline(std::cin, theInput);


    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {


        std::cout << "Error" << std::endl;


        if( theInput.find_first_not_of("0123456789") == std::string::npos) {

            std::cin.clear();

            std::cin.ignore(256,'\n');

        }


        std::getline(std::cin, theInput);

    }


    std::string::size_type st;

    inputAsInt = std::stoi(theInput,&st);

    std::cout << inputAsInt << std::endl;

    return 0;

}


查看完整回答
反對 回復 2019-10-11
  • 3 回答
  • 0 關注
  • 603 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號