虽然循环不终止?

While loop doesn't terminate?

本文关键字:终止 循环      更新时间:2023-10-16

我想知道为什么这个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;

}

程序总是等待您添加更多的输入,所以它不会终止。有几种方法可以解决这个问题:

  • 让程序查找一个特定的关键字,如"退出"或"退出",甚至只是一个空格,并键入该终止。这很简单,但不是很优雅。
  • 发送一个"流结束"指示符作为你输入的唯一内容。在linux和unix中,您只需键入Ctrl-D,这将表明您已经关闭了标准输入。正如一些评论所说,Ctrl-Z是Windows的文件结束说明符,如果你正在使用它。

你的程序永远不会结束,因为你的外部循环永远在运行。

可能的解决办法:

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循环。也许最好将它们放在函数中。

你的程序表现出未定义的行为,因为它在这个循环中读取了数组的末尾:

for (int i = 0; i < 10; i++){
   if (roman_thousands[i] == line){
       cout << "The Arabic equivalent of " 
            << line <<" is: " << i << 0 << 0 << 0 << endl;
    }
}