Reputation: 215
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!
Upvotes: 0
Views: 1179
Reputation: 361812
You can write a stringbuilder
utility in such a way that you would be able to use it as:
myArray[i][j] = stringbuilder() << "(" << i << "," << j << ")";
//other examples
std::string s = stringbuilder() << 25 << " is greater than " << 5;
f(stringbuilder() << a << b << c); //f is : void f(std::string const&);
where stringbuilder
is defined as:
struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
Note that if you're going to use std::stringstream
many times in your code, the stringbuilder
reduces the verbosity of your code. Otherwise, you can use std::stringstream
directly.
Upvotes: 3
Reputation: 258688
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 not operator +
.
Regardless, use a std::stringstream
.
std::stringstream ss;
ss << "(" << i << "," << j << ")";
myArray[i][j] = ss.str();
Upvotes: 4