2015-10-06 39 views
0

好吧,我正在做一項任務,並且感到沮喪。該任務讓我向用戶詢問一個數字,然後說出數字是偶數還是奇數,但如果用戶輸入「完成」,程序將退出。檢查Char/Int

所以我的問題是如何檢查字符/ int在同一時間的輸入,然後決定它是什麼。

// ConsoleApplication2.cpp : Defines the entry point for the console application. 
//  
#include "stdafx.h" 
#include <iostream> 
#include <string> 
bool isEven(int userAnswer); 
using namespace std; 
int userAnswer; 

int main() 
{ 
    cout << "Which number would you like to check?" << endl; 
    cin >> userAnswer; 

    if (isEven(userAnswer) == false) 
    { 
     cout << userAnswer << " is a odd number." << endl; 
    } 
    else if (isEven(userAnswer) == true) 
    { 
     cout << userAnswer << " is a even number." << endl; 
    } 

    cin.get(); 
    cin.get(); 

    return 0; 
} 

bool isEven(int userAnswer) 
{ 
    if (userAnswer % 2 == 0) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
+0

'int userAnswer;'應該在'main'內部聲明而不是全局變量,並且您不需要'else if'而只需要'else',因爲只有兩種可能性函數調用('== false')和否定,更常用的是'!isEven(userAnswer)')。 – crashmstr

+0

我收緊你先檢查「完成」字符串,然後如果沒有完成,將字符串轉換爲int並進行偶數/奇數檢查 – MokaT

回答

3

讀入字符串(在兩種情況下都起作用),然後自己分析字符串。

2

如果done位於字符串中,則讀入std::string並退出。否則轉換爲int並繼續按原樣。提示:請參見std::stoi

+0

否。*不要*使用stoi,請使用std :: stringstream '並檢查插入整數是否失敗。 – Casey

+0

爲什麼你更喜歡'std :: stringstream'? – cdmh

+0

它的類型更安全,從接口的角度來看就像'std :: cin'和'std :: cout'一樣工作。 – Casey