尝试在 C 中打印字符串变量时编译器错误
Compiler error while trying to print a string variable in C
#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 MENUn"
<< "-------------------------n"
<< "p) Play Gamen"
<< "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) Rockn"
<< "2) Papern"
<< "3) Scissorsn"
<< "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 '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
为了澄清起见,这就是讲师希望我们创建程序的方式。我们不允许简单地接受用户的输入作为字符串(稍后在程序中,我们必须对值进行比较,我们还不知道如何比较字符串)。提前谢谢。
#include<string>
In code:do following changes
cout << "You chose: "<<convertToString(playerChoice).c_str() << endl;
cout << "The computer chose: "<<convertToString(computerChoice).c_str()<< endl;
您需要
添加#include <string>
cout <<"You chose: " <<convertToString(playerChoice) <<endl;
convertToString(playerChoice) 返回一个字符串类型,如果不包括不能包含 cout<<(字符串类型)
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- C++编译器是否优化了顺序静态变量读取?
- 有没有办法强制C++编译器将变量存储在寄存器中?
- 如果函数包含静态变量,为什么编译器不执行内联?
- 现代c++编译器会优化不可变的临时变量吗
- 是否允许编译器优化掉局部易失性变量
- 现代编译器会优化只引用对象子集的局部变量吗
- (C++)for循环中的空初始语句是否保存所有编译器中变量的上一次初始化
- 如何在编译器时动态获取元组内的变量类型C++?
- 奇怪的未声明变量编译器错误
- 是否可以将移动的变量标记为不再可用,并在使用它时收到编译器警告?
- 编译器是否足够聪明,以至于 std::move 变量超出范围?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 使用常量变量作为维度将矩阵声明为类成员时出现编译器错误
- Eclipse 编译器有没有办法将变量中的地址字段显示为整数值?
- 为什么编译器并不总是优化局部变量?
- 关于基类中的显式模板实例化和静态变量:编译器错误或规范的有效解释
- 无法引用专用静态成员变量:编译器错误