insert element: hello
例如我输入单词hello,它应该将字母放在每个后续索引中。我试过字符串,但它似乎压缩到一个索引,并给我意想不到的行为,如果我试图添加更多。
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 a b c d e
1 f g h i j k l m n s
2 h e l l o
==========================================
这是我糟糕的代码:
#include<iostream>
std::string myarray[3][10] = {{"1","2","3","4","5","a","b","c","d","e"},
{"f","g","h","i","j","k","l","m","n","s",},
{" "," "," "," "," "," "," "," "," "," ",}};
void displaygrid();
using namespace std;
int main (){
int col = 0;
char insert; //i tried strings but it was out of order
displaygrid();
cout<<"==========================================" <<endl;
cout<<"insert element: ";
cin>>insert;
myarray[2][col] = insert;
cout<<"Insert Successful!" <<endl;
col++;
displaygrid();
}
void displaygrid(){
cout<<endl;
for(int z = 0; z<10; z++){
cout<<" "<<z;
}
cout<<endl;
for(int x = 0; x<3; x++){
cout<<x;
for(int y = 0; y<10; y++){
cout<<" " <<myarray[x][y] <<" ";
}
cout<<endl;
}
}
答案 0 :(得分:0)
如@super所述,您可以使用字符串执行此操作。以下是一些可以帮助您入门的代码。
#include<iostream>
#include<string>
int main(){
std::string grid;
//get insert element
std::cout << "Insert Element: ";
std::cin >> grid;
//print the grid using rowLength for number of elements along x
const int rowLength = 10;
int run = 0;
for(auto x : grid)
{
std::cout << x << " | ";
run++;
if(run >= rowLength)
{
std::cout << std::endl;
run = 0;
}
}
}