'Want to specify a specific character in a char array
I have made a char array, where I basically enter the number of rows and columns, and enter in the letters for each row and column, such as x and y. Basically, like an normal array but with letters. After I enter the letters and finish with the array, I want to enter 2 numbers to specify a specific char in the array. For example, my array is 3x3. I fill my array with the characters x and y. After I do that, I enter 2 2. At row 2 and column 2, the letter there is y. So I want to print out y.
Here is my code.
#include <iostream>
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
char n[x][y];
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
cin>>n[i][j];
}
}
int a,b;
cin>>a>>b;
cout<<n[a][b];
}
Solution 1:[1]
The main problem with your given program is that in Standard C++ the size of an array must be a compile time constant. This means that the following is not valid:
int x,y;
cin>>x>>y;
char n[x][y];//not standard C++ because x and y are not constant expressions
To solve this you can use a std::vector<char> as shown below:
#include <iostream>
#include<vector>
int main()
{
int x,y;
std::cin>>x>>y;
//create a 2D vector
std::vector<std::vector<char>> n(x, std::vector<char>(y));
//iterate through rows
for(auto& row: n)
{
//iterate through each element in the row
for(auto& col: row)
{
std::cout<<"enter element: "<<std::endl;
std::cin>>col; //take input from user
}
}
int a,b;
std::cout<<"a and b"<<std::endl;
std::cin>>a>>b;
std::cout<<"element at position: "<<a<<" "<<b <<" is: "<<n[a][b];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
