我想知道为什么这个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;
}
答案 0 :(得分:6)
程序总是等待您添加更多输入,因此它不会终止。有几种方法可以解决这个问题:
答案 1 :(得分:2)
你的程序永远不会结束,因为你的外循环永远运行。
可能的解决方法:
while (cin >> line)
{
int i = 0;
if (line == "quit") break;
while(line[i])
{
c = line[i];
c = (toupper(c));
line[i] = c;
i++;
}
// run for loops
}
然后你将不得不调用所有这些for循环。可能最好把它们放在一个功能中。
答案 2 :(得分:0)
您的程序显示未定义的行为,因为它在此循环中读取数组的末尾:
for (int i = 0; i < 10; i++){
if (roman_thousands[i] == line){
cout << "The Arabic equivalent of "
<< line <<" is: " << i << 0 << 0 << 0 << endl;
}
}