【问题标题】:Why doesn't my function return a string?为什么我的函数不返回字符串?
【发布时间】:2017-10-09 04:11:26
【问题描述】:

我创建了一个函数 (displayChoice) 来生成一个随机数,然后创建另一个函数 (getComputerChoice) 来获取该数字并将该随机整数分配给一个字符串。当我打印该字符串时,什么都没有出现。我不知道为什么会发生这种情况。

#include <iostream>
#include <limits>
#include <ctime>
#include <cstdlib>
int getComputerChoice();
std::string displayChoice(int dChoice);


int main()
{

std::string comp = displayChoice(getComputerChoice());
std::cout << comp;
}
int getComputerChoice()
{
  srand(time(NULL));
  int ranCompChoice = (rand() % 6) + 1;
  return ranCompChoice;
}


std::string displayChoice(int dChoice)
{
std::string ChoiceString;
if (dChoice == 1)
{
    ChoiceString == "rock";

}
else if (dChoice == 2)
{
    ChoiceString == "paper";
}
else if (dChoice == 3)
{
    ChoiceString == "scissors";
}
else if (dChoice == 4)
{
    ChoiceString == "lizard";
}
else
{
    ChoiceString == "Spock";
}
    return ChoiceString;
}

【问题讨论】:

  • 请正确缩进您的代码。此外,您可能需要在打印输出的末尾添加&lt;&lt; std::endl。
  • C++ 再次成为 C++,让你做nops。

标签: c++ string function


【解决方案1】:

你必须使用赋值运算符。

例如 ChoiceString = "Spock";

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2020-07-06
    • 2017-04-15
    • 1970-01-01
    • 2016-05-12
    • 2019-10-12
    • 1970-01-01
    • 2021-05-12
    • 2016-01-18
    相关资源
    最近更新 更多