gpt4 book ai didi

c++ - 在特定情况下跳出循环

转载 作者:行者123 更新时间:2023-11-28 02:14:10 24 4
gpt4 key购买 nike

我正在编写一个代码,对于一行或几行字符串,查找整个输入是否只有“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;
}

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

关于c++ - 在特定情况下跳出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34558652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com