嘿,我是 c/c++ 的新手,希望我能被推向正确的方向以修复我的错误。
我正在创建一个打开文件并读取文件中的文本并将其放入字符串中的程序。从那里我创建了一个二维数组,通过获取字符串可以放入的最小完美平方的平方根来找到它的大小。现在我们到了我遇到麻烦的地方,从这一步我试图把使用以下代码将字符串逐列放入数组中。
char newarray[b][b]; //b being the square root of the closest perfect square.
57
58 //put string into arrray;
59 for(int row=0; row < b; row++)
60 {
61 for(int column=0;column < b; column++)
62 {
63 newarray[row][column] = newstring[row];
64 }
65 }
但是当我打印这个数组时,文本的每个字母都填满了该行中的每个元素。
即
string s= "supercalifragilistic";
char[5][5];
// I want it to come out like this
0 1 2 3 4 5
1 s u p e r
2 c a l i f
3 f r a g i
4 l i s t i
5 c
//but it comes out like this
0 1 2 3 4 5
1 s s s s s
2 u u u u u
3 p p p p p
4 e e e e e
5 r r r r r
最佳答案
对源字符串使用不同的索引。
char newarray[b][b]; //b being the square root of the closest perfect square.
//put string into arrray;
int i=0;
for(int row=0; row < b; row++)
{
for(int column=0;column < b; column++, i++)
{
newarray[row][column] = newstring[i];
}
}
关于c++ - C/C++ 将字符串放入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30094578/