C ++使用char输入到int终止循环 [英] C++ Terminate loop using a char input to int
问题描述
我试图输入值到一个大小为10的数组,但问题是,我想要如果用户想要输入4x4矩阵,他不需要完成,直到数组中的第10个元素,他可以简单地按f或任何字符,我试图使if(input =='f'),但它循环,直到数组的结尾。
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; }
推荐答案
您必须更改您阅读输入的策略的值。将令牌作为字符串读取。如果字符串的第一个字符是'f',则中断循环。
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++;
}
}
这篇关于C ++使用char输入到int终止循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!