【问题标题】:How do I test functions with an if statement如何使用 if 语句测试函数
【发布时间】:2016-03-02 03:48:23
【问题描述】:

您好,我需要一些代码方面的帮助。我需要测试一个函数,但每次尝试编译时都会出现编译器错误。这是我得到的,错误:不同指针类型'void()()'和'const char'之间的比较缺少强制转换。 这是我的代码。

#include <iostream>
using namespace std;

void getInput();
bool gameGoing = true;

int main()
{
do{

    cout << "hello world this is a test.\n";
    getInput();
    if(getInput == "false")
    {
        return 0;
    }

}while(gameGoing = true);
}

void getInput()
{
string userInput;
cin >> userInput;
}

【问题讨论】:

  • 完全不清楚你想要实现什么。您的函数没有返回值,并且您正在尝试将函数指针与字符串进行比较

标签: c++ function compiler-errors


【解决方案1】:

应该是

#include <iostream>
using namespace std;

string getInput();
bool gameGoing = true;

int main()
{
    do
    {

        cout << "hello world this is a test.\n";
        if(getInput() == "false")
            return 0;

    } while(gameGoing == true);
}


string getInput()
{
    string userInput;
    cin >> userInput;
    return userInput;
}

我改变了什么:

  • getInput 函数添加了返回类型,这样它的结果就不会被忽略
  • 修复了 if 比较以实际比较 getInput 函数的结果与 "false"
  • 修复了 while 条件以将 gameGoingtrue 值进行比较而不是覆盖它

【讨论】:

  • while(true == gameGoing)
  • 另外,main 在循环之后应该有一个return 0;(如果没有其他原因,除了良好的编程习惯)
  • @UnholySheep:C++ 中不需要,如果函数末尾没有返回,则返回 0。
  • @init_js while (gameGoing)
猜你喜欢
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多