AlexanderPepper AlexanderPepper - 2 months ago 15x
C++ Question

Error C2679: "binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)"

my little brother is currently learning how to code in C++, and as a way to test different ways Arrays can be use, he started a program that would have the computer generate a random number, then output a particular emotion (stored in an array) based on that number. For some reason however, the section of code where the output goes doesn't want to work the way I suggested.

The way I thought it should be written was 'cout << "I'm" << emotion[x] << endl;', which I'm sure has worked for me in the past, but for some reason the computer won't accept that. I haven't actually coded in C++ for a while, so maybe something has changed or I forgot how 'cout' works.

It's probably something super simple and stupid that I should have caught already, but I just can't see it. Here's the rest of the code, in case the problem is somewhere further up the line.

#include <iostream>
#include <ctime>
#include <fstream>

using namespace std;

string emotion[6];

int main() {
emotion[0] = "Happy";
emotion[1] = "Sad";
emotion[2] = "Angry";
emotion[3] = "Fearful";
emotion[4] = "Disgusted";
emotion[5] = "Suprised";


int x;
x = (rand() % 6);

cout << "I'm " << emotion[x] << endl;



Exactly as you thought, a simple mistake indeed. You need to #include <string> for it to work as you expect and Here Is Why.

You might also need to #include <cstdlib> for srand and rand and Here is why you may not need it.