Reputation: 64
I'm trying to input values into an array of size 10, but the problem here is that I want if the users wants to enter 4x4 matrix, he doesn't need to complete till the 10th element in the array, he can simply press 'f' or any character, I tried to make if(input == 'f') but it loops till the end of the array. How can this be solved?
int main() {
int input,flag=0, size=0;
int matrix[10][10] = {0};
for(int i=0; i<10; i++) {
for(int j=0; j<10;j++) {
cout << "Please enter data for Row " << i << " Column " <<j << " (-200 to terminate): \n";
cin >> input;
if(input == -200) {
flag = 1;
break;
}
else
matrix[i][j] = input;
}
if(flag == 1)
break;
size++;
}
cout << "The determinant of the matrix is: " << determinant(matrix,size) << "\n";
return 0; }
Upvotes: 1
Views: 1590
Reputation: 1361
As R Sahu told that You have to change your strategy of reading the input. So you can also use stringstream to get the solution
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int input,flag=0, size=0;
int matrix[10][10] = {0};
string s;
for(int i=0; i<10; i++) {
for(int j=0; j<10;j++) {
cout << "Please enter data for Row " << i << " Column " <<j << " (-200 to terminate): \n";
cin >> s;
stringstream ss(s);
ss>>input;
if(ss==0)
{
if(s == "f") {//user don't want to enter further input
flag = 1;
break;
}
else
{
//invalid data so you need to reset the value of i and j;
}
}
else
{
cout<<"Input:"<<input<<endl;
matrix[i][j] = input;
}
}
if(flag == 1)
break;
size++;
}
Upvotes: 0
Reputation: 1782
This happens because the exit criteria is the value -200, when you input -200 then all cylces stop working, finish.
Upvotes: 0
Reputation: 206717
You have to change your strategy of reading the input. Read the token as a string. If the first character of the string is 'f', the break out of the loop. Otherwise, extract the number from the string.
int main()
{
std::string input;
int flag=0;
int size=0;
int matrix[10][10] = {0};
for(int i=0; i<10; i++) {
for(int j=0; j<10;j++) {
std::cout << "Please enter data for Row " << i << " Column " <<j << " (f to terminate): \n";
std::cin >> input;
if ( input[0] == 'f' ){
flag = 1;
break;
}
else
matrix[i][j] = atoi(input.c_str());
}
if(flag == 1)
break;
size++;
}
}
Upvotes: 1