I want to start off by saying that I have almost no experience with C++ but I am taking a college class for it this semester and was just sort of messing around so that I am a little better prepared for the class. I know a good amount of Java but almost no C++.
Basically, I want to make some integers part of a string that will go into a string 2D Array. Then I want to print out just to make sure that everything is in the array…I realize that the second for loop isn’t really necessary but I put it there anyway.
My problem is that I keep getting an error message when trying to do:
myArray[i][j] = "(" << i << "," << j << ")";
Specifically, it tells me:
error: invalid operands of types 'const char*' and 'const char [2]' to binary
'operator+'
I don’t understand this error nor do I know how to fix it…
Here is what I have.
int height = 5;
int width = 5;
string myArray[height][width];
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
myArray[i][j] = "(" << i << "," << j << ")";
}
}
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
cout << myArray[i][j] << " ";
}
}
I just want to know how to fix the error and then I would also like to know specifically why I am getting said error. Thanks!
You get the error because that’s not the way to concatenate strings in C++. But the message is strange, since you appear to be using
operator <<and notoperator +.Regardless, use a
std::stringstream.