在特定情况下跳出循环

jumping outside loop in a specific case

本文关键字:跳出循环 在特定情况下      更新时间:2023-10-16

我正在编写一个代码,对于一行或几行字符串,查找整个输入是否只有"cool"行(第一行、第二行和最后一行字符串相同)、只有"uncool"行将两者混合。

我遇到的问题是,每当我输入偶数时,while循环就会终止。调试时我发现,就在跳出来之前,n的值为0,但我不明白这将如何结束循环。

这是代码:

#include <iostream>
using namespace std;
int main () {
    // Bool has control if we have found a cool line/non-cool line
    bool cool = false;
    bool uncool = false;
    int n; //lenght of input
    while (cin >> n) {
        if (cool and uncool) break; // we have found one of each so we know it is a mixed input
        else if (n%2 == 0) uncool = true; // if the lenght is even there is no middle string
        else {
            // we are trying to see if the middle and last string are equal to the first
            string comparing_string;
            cin >> comparing_string;
            string rest_of_sequence;
            bool this_is_cool = true;
            for (int i = n-2; i >= 0; i--) { // we input the rest of strings and compare them to the first
                cin >> rest_of_sequence;
                if ((i == n/2 or i == 0) and rest_of_sequence != comparing_string) this_is_cool = false;
            }
            if (this_is_cool) cool = true;
            else uncool = true;
        }
    }
    if (cool and uncool) cout << "both types" << endl;
    else if (cool and not uncool) cout << "all cool" << endl;
    else if (uncool and not cool) cout << "none cool" << endl;
}

感谢您的帮助!我目前在大学一年级,总是打开推荐的书籍/网页/视频继续学习:)

问题是,我认为程序会忽略while循环中不是整数的输入,但事实并非如此。

现在代码是正确的:

else if (n%2 == 0) {// if the lenght is even there is no middle string
            uncool = true;
            string just_passing_input;
            for (int i = n; i > 0; i--) cin >> just_passing_input;
        }

感谢您的反馈,我现在将继续学习。