我的问题是添加元素。如果我试图再次添加它只是替换最后一个添加位置。在添加时,它应该移动到下一个插槽/索引。
例如
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2|
Add element:m
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2| m
添加元素:n
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2| m n
这是我的代码:
#include<iostream>
#include<string>
std::string myarray[3][6] = {{"a","b","c","d","e","f"},
{"g","h","i","j","k","l"},
{" "," "," "," "," "," "}};
void display();
using namespace std;
int main(){
while(true){
display();
char add;
int rows = 2;
int cols = 6;
cout<<"==========================================" <<endl;
cout<<"Add element: ";
cin>>add;
int size = rows*cols;
myarray[0][size] = add;
cout<<"Adding Successful!" <<endl;
size=size+1;
}
}
//display
void display(){
cout<<endl;
for(int z = 0; z<6; z++){
cout<<" "<<z;
}
cout<<endl;
for(int x = 0; x<3; x++){
cout<<x <<"|";
for(int y = 0; y<6; y++){
cout<<" " <<myarray[x][y] <<" ";
}
cout<<endl;
}
}
答案 0 :(得分:1)
始终为元素myarray[0][size]
分配一个新值,在每次迭代中计算一个新的int size = rows*cols;
(size
= 12)。并且您正在从ist限制中访问Array
如果没有考虑任何其他问题,可能会修复此问题:
int col=0;
while (col < 6) {
display();
char add;
cout<<"==========================================" <<endl;
cout<<"Add element: ";
cin>>add;
myarray[2][col] = add;
cout<<"Adding Successful!" <<endl;
++col;
}
答案 1 :(得分:0)
问题在于他的代码部分
int rows = 2;
int cols = 6;
cout<<"==========================================" <<endl;
cout<<"Add element: ";
cin>>add;
int size = rows*cols;
myarray[0][size] = add
你需要像++行或++ cols这样的东西并调用
myarray[rows][cols] = add