2D 字符串数组 C++:整数串联成字符串

2D string Array C++: Integer Concatenation Into String

本文关键字:字符串 整数 数组 C++ 2D      更新时间:2023-10-16

我想首先说的是,我几乎没有C++的经验,但我这学期正在上大学课程,只是有点乱七八糟,以便为这门课做好更好的准备。我知道很多Java,但几乎没有C++。

基本上,我想使一些整数成为字符串的一部分,该字符串将进入字符串 2D 数组。然后我想打印出来只是为了确保所有内容都在数组中......我意识到第二个 for 循环并不是真的必要,但我还是把它放在那里。

我的问题是我在尝试执行时不断收到错误消息:

myArray[i][j] = "(" << i << "," << j << ")";

具体来说,它告诉我:

error: invalid operands of types 'const char*' and 'const char [2]' to binary 
       'operator+'

我不明白这个错误,也不知道如何解决它......

这是我所拥有的。

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] << "  ";
    }
}

只是想知道如何修复错误,然后我也想知道为什么我会收到上述错误。谢谢!

您会收到错误,因为这不是在C++中连接字符串的方法。但是消息很奇怪,因为您似乎正在使用operator <<而不是operator +

无论如何,请使用std::stringstream .

std::stringstream ss;
ss << "(" << i << "," << j << ")";
myArray[i][j] = ss.str();

您可以编写 stringbuilder 实用程序,以便能够将其用作:

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&);

其中stringbuilder定义为:

struct stringbuilder
{
   std::stringstream ss;
   template<typename T>
   stringbuilder & operator << (const T &data)
   {
        ss << data;
        return *this;
   }
   operator std::string() { return ss.str(); }
};

请注意,如果要在代码中多次使用 std::stringstream,则stringbuilder会降低代码的详细程度。否则,您可以直接使用std::stringstream