【问题标题】:Compiler error while trying to print a string variable in C尝试在 C 中打印字符串变量时出现编译器错误
【发布时间】:2013-10-19 05:09:34
【问题描述】:
#include <iostream>
#include <random>
#include <cstdlib>
#include <time.h>

using namespace std;

int getComputerChoice();
int getPlayerChoice();
string convertToString(int);

int main()
{
    int computerChoice, playerChoice;
    string choiceOne, choiceTwo;

    cout << "ROCK PAPER SCISSORS MENU\n"
         << "-------------------------\n"
         << "p) Play Game\n"
         << "q) Quit" << endl;

    srand (time(NULL));

    computerChoice = getComputerChoice();
    playerChoice = getPlayerChoice();

    cout << "You chose: " << convertToString(playerChoice) << endl;
    cout << "The computer chose: " << convertToString(computerChoice) << endl;

    system("PAUSE");
    return 0;
}

int getComputerChoice()
{
    int choiceComp = (rand() % 3) + 1;
    return choiceComp;
}

int getPlayerChoice()
{
    int choicePlayer;

    do {
    cout << "Rock, Paper or Scissors?\n"
         << "1) Rock\n"
         << "2) Paper\n"
         << "3) Scissors\n"
         << "Please enter your choice: " << endl;
    cin >> choicePlayer;
    } while (choicePlayer < 1 || choicePlayer > 3);

    return choicePlayer;
}

string convertToString(int choiceAsInt)
{
    string choiceName;

    if (choiceAsInt == 1)
    {
        choiceName = "Rock";
    }
    else if (choiceAsInt == 2)
    {
        choiceName = "Paper";
    }
    else choiceName = "Scissors";

    return choiceName;
}

到目前为止,这是我的代码。我想要做的是使用一个函数将用户的输入(它是一个 int)转换为一个用于打印的字符串。谁能解释为什么我当前的代码导致编译器错误?这是错误告诉我的内容:Error 2 error C2679: binary '&lt;&lt;' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) 为了澄清起见,这就是讲师希望我们创建程序的方式。我们不允许简单地接受用户的输入作为字符串(稍后在程序中我们必须对值进行比较,我们还不知道如何比较字符串)。提前致谢。

【问题讨论】:

  • 你忘了#include &lt;string&gt;

标签: c++ string printing cout


【解决方案1】:
#include<string>

In code:do following changes

 cout << "You chose: "<<convertToString(playerChoice).c_str() << endl;
 cout << "The computer chose: "<<convertToString(computerChoice).c_str()<< endl;

【讨论】:

    【解决方案2】:

    您需要添加#include &lt;string&gt;

    【讨论】:

    • 真的就这么简单,我觉得自己像个白痴。谢谢。
    【解决方案3】:

    cout

    convertToString(playerChoice) 返回一个字符串类型,如果不包含则不能cout

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 2018-11-26
      相关资源
      最近更新 更多