我試圖將值輸入到大小爲10的數組,但這裏的問題是,如果用戶想要輸入4x4矩陣,他不需要完成直到數組中的第10個元素,他可以簡單地按'f'或任何字符,我試圖讓if(input =='f'),但它循環直到數組的末尾。這怎麼解決?C++終止循環使用char輸入到int
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; }
'的atoi(input.c_str());'可以返回一個無效數據的情況下,用戶輸入的不是'F'其他任何字符串 – rajenpandit