2D 字符串数组 C++:整数串联成字符串
2D string Array C++: Integer Concatenation Into String
我想首先说的是,我几乎没有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
。
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 尝试将字符串/字符转换为整数会产生意外结果
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 如何从C++中的格式化字符串派生整数?
- 如何使用C++将字符串中的字符转换为整数变量
- 向量值(字符串和整数)求和C++
- 如何从字符串C++读取多个整数
- 如何将整数字符串转换为整数的二维向量?
- 输入验证以筛选出字符、字符串和一系列整数
- 有没有办法在C++中将字符串和整数相乘?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- C++字符串大小减去整数不是预期值,为什么?
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- C++ runtime_exception字符串 + 整数
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- 使用next_permutation函数后如何保存字符串/整数
- 使用fstream和sstream一起从文件中分离字符串/整数