gpt4 book ai didi

c++ - 将字符串转换为 char 二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:52 29 4
gpt4 key购买 nike

我想知道有谁知道如何将字符串转换为二维数组?这是我的尝试:

string w;
char s[9][9];
int p=0;
getline(cin, w);
while(p != w.size())
{
for (int k = 0; k < 9; k++)
{
for(int j = 0; j < 9; j++)
{
s[k][j] = w[p];
p++;
}
}
}
cout << "nums are: " << endl;
for(int k = 0; k < 9; k++)
{
for(int j = 0; j <9; j++)
{
cout << s[k][j];
}
}

但是数字打印不正确。我希望 s[k][j] 打印出 w 中的所有内容,但它只是打印出乱码。我还注意到,如果我执行 string[81],则会出现一大堆错误。谁能帮帮我?谢谢。

最佳答案

试试这个:

const int NUM_ROWS = 9;
const int NUM_COLS = 9;

string w;
char s[NUM_ROWS][NUM_COLS];

getline(cin, w);

if (w.size() != (NUM_ROWS * NUM_COLS))
{
cerr << "Error! Size is " << w.size() << " rather than " << (NUM_ROWS * NUM_COLS) << endl;
exit(1);
}

for (int count = 0; count < w.size(); count++)
{
if (!isdigit(w[count]) && w[count] != '.')
{
cerr << "The character at " << count << " is not a number!" << endl;
}
}

for (int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
s[row][col] = w[col + (row * NUM_COLS)];
}
}

cout << "Nums are: " << endl;

for(int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
cout << s[row][col] << " ";
}

cout << endl;
}

根据我们的聊天记录,您可能需要:

const int NUM_ROWS = 9;
const int NUM_COLS = 9;

string w;
char s[NUM_ROWS][NUM_COLS];

while (!cin.eof())
{
bool bad_input = false;

getline(cin, w);

if (w.size() != (NUM_ROWS * NUM_COLS))
{
cerr << "Error! Size is " << w.size() << " rather than " << (NUM_ROWS * NUM_COLS) << endl;
continue;
}

for (int count = 0; count < w.size(); count++)
{
if (!isdigit(w[count]) && w[count] != '.')
{
cerr << "The character at " << count << " is not a number!" << endl;
bad_input = true;
break;
}
}

if (bad_input)
continue;

for (int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
s[row][col] = w[col + (row * NUM_COLS)];
}
}

cout << "Nums are: " << endl;

for(int row = 0; row < NUM_ROWS; row++)
{
for(int col = 0; col < NUM_COLS; col++)
{
cout << s[row][col] << " ";
}

cout << endl;
}
}

关于c++ - 将字符串转换为 char 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12992600/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com