我想知道爲什麼這個while循環不允許我的程序終止?while循環不終止?
據我所知(雖然我很可能是錯的)條件while (cin >> line)
檢查我的輸入流爲一個字符串,然後運行我的循環,直到輸入中找不到其他字符串。然而,在測試我的代碼後,我得到正確的輸出,但是我的循環從未終止任何想法,爲什麼?
#include <cstdlib>
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string roman_digits[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
string roman_tens [] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
string roman_hundreds [] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
string roman_thousands [] = {"", "M","MM", "MMM"};
string line;
char c;
cout << "Type in a Roman numeral: ";
// Loops through inputted Roman Numerals.
while (cin >> line){
int i = 0;
// Loops through a Roman numeral and changes it to uppercase.
while(line[i]){
c = line[i];
c = (toupper(c));
line[i] = c;
i++;
}
// Loops through checking roman numeral with the thousands array and if there is a match prints out the equivalent arabic number.
for (int i = 0; i < 10; i++){
if (roman_thousands[i] == line){
cout << "The Arabic equivalent of "
<< line <<" is: " << i << 0 << 0 << 0 << endl;
}
}
// Loops through checking roman numeral with the hundreds array and if there is a match prints out the equivalent arabic number.
for (int i = 0; i < 10; i++){
if (roman_hundreds[i] == line){
cout << "The Arabic equivalent of " << line << " is: " << i << 0 << 0 << endl;
}
}
// Loops through checking roman numeral with the tens array and if there is a match prints out the equivalent arabic number.
for (int i = 0; i < 10; i++){
if (roman_tens[i] == line){
cout << "The Arabic equivalent of " << line << " is: " << i << 0 << endl;
}
}
// Loops through checking roman numeral with the digits array and if there is a match prints out the equivalent arabic number.
for (int i = 0; i < 10; i++){
if (roman_digits[i] == line){
cout << "The Arabic equivalent of " << line << " is: " << i << endl;
}
}
}
return 0;
}
「不過我的測試代碼後,我得到正確的輸出,但我的循環永遠不會終止」 - 你怎麼會測試你的代碼? – Arun
您是否發送EOF(CtrlZ,CtrlD等,取決於您的終端和平臺)到標準輸入? – WhozCraig
重複:http://stackoverflow.com/questions/5360129/the-question-on-while-cin –