如何才能使我的功能恢复正确或错误

时间:2013-10-02 20:02:05

标签: c++ function return-value

我是C ++的新手,我真的遇到了这个问题: 当用户输入2个数字EX:1和2时,代码必须弄清楚第一个数字是否与第一个数字相比更大,问题是代码不会将真或假带为文本把它作为数字:/ (0 =假1 =真)

代码在这里:

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

bool GraterFunct(int num1, int num2);

int main(int argc, char** argv)

{
    std::cout <<" \n Hello there! This is a test to test how good you are with math. \n ";
    std::cout <<" Now enter G or L (Grater, less) to know if a number is grater or less than the number you choose \n ";
    char answer [1];
    std::cin >> answer;

    if(answer == "G" || "g")
    {
        int number1;
        int number2;
        std::cout << "You selected: Grater than, \n";
        std::cout << "Now type 2 numbers and see which one is grater than the other one. \n" << std::endl;
        std::cin >> number1;
        std::cout << "Your first number: " << number1 << std::endl;
        std::cout << "Select your second number \n";
        std::cin >> number2;
        std::cout << "The answer is: " << GraterFunct(number1, number2);
    }

    return 0;
}

bool GraterFunct(int num1, int num2)
{
    if(num1 >= num2)
    {
        {
            return true;
        }
    }
    else
    {
        if(num2 >= num1)
        {
            return false;
        }
    }
}

请帮忙!提前谢谢!

1 个答案:

答案 0 :(得分:1)

要将布尔值格式化为truefalse,您可以使用std::ios_base::boolalpha操纵器设置std::boolalpha标记:

std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n';

如果您是像我这样的非英语母语人士,您可能想要更改这些值的格式。假设安装了合适的区域设置,您只需imbue()到流中,或者您可以使用所需的truefalse呈现自己的区域设置,例如:

#include <iostream>
#include <locale>

class numpunct
    : public std::numpunct<char>
{
    std::string do_truename() const { return "wahr"; }
    std::string do_falsename() const { return "falsch"; }
};

int main()
{
    std::cout.imbue(std::locale(std::locale(), new numpunct));
    std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n';
}

顺便说一下,总是需要验证输入是否成功,例如:

if (std::cin >> number1) {
    // deal with the successful input here
}
else {
    // deal with the wrong input here
}