2015-10-06 58 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