[英]static 2d array, adding elements
My problem is in adding elements. 我的问题是添加元素。 If I tried to add again it's just replacing the last add position.
如果我尝试再次添加,则只是替换最后一个添加位置。 where when adding, it supposed to be moving to the next slot/index.
在添加位置时,它应该移至下一个广告位/索引。
for example 例如
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
Add element:n 添加元素:n
0 1 2 3 4 5
0| a b c d e f
1| g h i j k l
2| m n
here is my code: 这是我的代码:
#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;
}
}
Always the element myarray[0][size]
is assigned a new value where in each iteration a new int size = rows*cols;
始终为元素
myarray[0][size]
分配一个新值,其中在每次迭代中,新的int size = rows*cols;
is calculated ( size
= 12). 计算得出(
size
= 12)。 And your are accessing the Array out of ist limits 而且您正在访问阵列而超出了其限制
Without any of the other issues taking into account this might be fixed: 如果不考虑其他任何问题,则可以解决此问题:
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;
}
The problem is int his part of code 问题是他的代码部分
int rows = 2;
int cols = 6;
cout<<"==========================================" <<endl;
cout<<"Add element: ";
cin>>add;
int size = rows*cols;
myarray[0][size] = add
; ;
You need something like ++rows or ++cols and call 您需要++ rows或++ cols之类的东西,然后调用
myarray[rows][cols] = add
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.