如何插入一个单词并将字母放在2D数组中的不同索引中
how to insert a word and place the letters in different index in 2d array
insert element: hello
例如,i输入单词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;
}
}
正如@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;
}
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 使用指针算法修改函数中的 2D 数组
- 在C++中初始化和打印 2D 数组
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- C++ 2D 数组写入多个位置
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 如何从initializer_list初始化 2D 数组
- 交换函数不是在 C++ 中交换 2D 数组的元素