enter like matrix
Sep 12, 2017 at 4:56pm UTC
the code works fine but i want to input the values like a matrix but instead it inputs in a weird way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include<iostream>
using namespace std;
int main()
{
int r,c;
int *value;
cout<<"Enter number of rows" ;cin>>r;
cout<<endl;
cout<<"Enter number of columns" ;cin>>c;
cout<<endl;
value=new int [r*c];
if (!value)
cout<<"Out of memory" <<endl;
cout<<"Enter 2-D array" <<endl;
for (int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
cin>>value[i*c+j];
cout<<"\t" ;
}
cout<<endl;
}
cout<<"Displaying your 2-D array" <<endl;
for (int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
cout<<value[i*c+j]<<"\t" ;
}
cout<<endl;
}
return 0;
}
The output is perfect.
Last edited on Sep 12, 2017 at 5:00pm UTC
Sep 13, 2017 at 6:59am UTC
cin outputs all user input including the newline:
Enter number of rows2
Enter number of columns2
Enter 2-D array
1
2
3
4
Displaying your 2-D array
1 2
3 4
This is also possible:
Enter number of rows2
Enter number of columns2
Enter 2-D array
1 2 3 4
Displaying your 2-D array
1 2
3 4
Unfortunately there is nothing you can do to change this behavior of cin. If you want another input scheme you need to do this in another way like pdcurses.
Sep 13, 2017 at 7:05am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include<iostream>
int main()
{
std::cout << "\nEnter number of rows: " ;
int r {};
std::cin >> r;
std::cout << "Enter number of columns: " ;
int c {};
std::cin >> c;
int * value = new int [r*c];
if (!value) {
std::cout << "Out of memory\n" ;
return 0;
}
std::cout << "Enter 2-D array - please press ENTER after each value:\n" ;
for (int i=0; i<r; i++)
{
for (int j=0;j<c;j++)
{
std::cout << "\tPlease enter data for row " << i+1
<< " column " << j+1 << ": " ;
std::cin >> value[i*c+j];
}
std::cout << '\n' ;
}
std::cout << "Displaying your 2-D array:\n" ;
for (int i=0; i<r; i++)
{
for (int j=0; j<c; j++)
{
std::cout << value[i*c+j]<<"\t" ;
}
std::cout << '\n' ;
}
return 0;
}
Please have a look at the warnings about your indentation: there's a subtle error in your code logic.
Topic archived. No new replies allowed.