【问题标题】:Checking for Char/Int检查字符/整数
【发布时间】:2016-01-03 12:54:53
【问题描述】:

好的,所以我正在做一项任务并且感到很沮丧。作业要我向用户询问一个数字,然后说出该数字是偶数还是奇数,但如果用户键入“完成”,程序将退出。

所以我的问题是如何同时检查字符/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;
    }
}

【问题讨论】:

  • int userAnswer; 应该在 main 中声明而不是全局变量,并且您不需要 else if 而只需要 else 因为函数调用只有两种可能性(== false 和它的否定。更惯用的是!isEven(userAnswer))。
  • 我建议您先检查“完成”字符串,如果没有完成,将字符串转换为 int 并进行偶数/奇数检查

标签: c++ loops if-statement while-loop evaluation


【解决方案1】:

读入一个字符串(在这两种情况下都有效),然后自己解析字符串。

【讨论】:

    【解决方案2】:

    读入std::string 并在done 在字符串中时退出。否则请转换为int 并照常进行。提示:见std::stoi

    【讨论】:

    • 没有。 不要使用stoi,使用std::stringstream并检查插入整数是否失败。
    • 为什么更喜欢std::stringstream
    • 它的类型更安全,从界面的角度来看,它就像std::cinstd::cout
    • 我不明白为什么它更安全。有参考吗?
    • 我的立场是正确的。我的印象是stoi 像旧的atoi 一样工作,(等等)功能(即可怕)。似乎 stoi 和类似的 stolstoll 是为 C++11 添加的,并且很健壮。 +1。
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2016-04-06
    • 1970-01-01
    • 2011-03-23
    相关资源
    最近更新 更多