假如输入8行8列的字符串,我想将其赋给数组,但是,总是会出现?,数组为空的情况。这是因为每行字符串的末尾会有一个“\0”吗?
我应该怎么避免将“\0”赋给二维数组?


假如输入8行8列的字符串,我想将其赋给数组,但是,总是会出现?,数组为空的情况。这是因为每行字符串的末尾会有一个“\0”吗?
我应该怎么避免将“\0”赋给二维数组?


关注【以下回答由 GPT 生成】
#include <iostream>
#include <string>
int main() {
std::string input = "abcdefgh 12345678\n"
"ijklmnop 23456789\n"
"qrstuvwx 34567890\n"
"yzabcdefg 45678901\n"
"hijklmno 56789012\n"
"pqrstuvw 67890123\n"
"xyzabcd 78901234\n"
"efghijk 89012345";
const int rows = 8;
const int cols = 8;
char array[rows][cols];
int index = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
while (input[index] == ' ' || input[index] == '\n' || input[index] == '\r') {
++index; // skip spaces and newlines
}
array[i][j] = input[index];
index++;
}
}
// Print the 2D array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
这段代码可以解决你的问题。首先,我们定义了一个8行8列的字符串,并且创建了一个8行8列的二维数组。然后使用两层循环遍历字符串,并且使用一个索引变量来跳过空格和换行符。在每个非空格非换行符的字符处,将其赋给二维数组。最后,再遍历二维数组并打印每个元素,可以看到正确地避免了空格和末尾的"\0"。
【相关推荐】