我正在编写一个代码,对于一行或几行字符串,查找整个输入是否只有“酷”(它的第一个中间和最后一个字符串是相同的)行,只有“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;
}
任何帮助表示赞赏!我目前正处于大学的第一年,并且总是对推荐的书籍/网页/视频开放以继续学习:)
答案 0 :(得分:2)
问题在于我认为程序会忽略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;
}
感谢您提供有用的反馈,我现在将继续学习。