在特定情况下跳出循环
jumping outside loop in a specific case
我正在编写一个代码,对于一行或几行字符串,查找整个输入是否只有"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++ 选择排序在特定情况下不起作用
- 在儿童的特定情况下,向下渗透MIN二进制堆失败
- Qt TcpSocket::readyRead 在特定情况下未触发
- C++ 在一种特定情况下替代无效*
- “overload_cast”在特定情况下失败
- 为什么在某些特定情况下具有多个线程(并行处理)会降低性能
- 在此特定情况下,使用unique_ptr的char数组
- 在特定情况下,static_cast和dynamic_cast的不同行为
- 在这种情况下,while 循环如何工作
- 在特定情况下,指针删除和铸造之间的关系不清楚
- 如何在服务器端验证用户请求(在我的特定情况下)
- LeetCode210.为什么我的代码在特定情况下是错误的
- 在特定情况下,班级驱动器
- 双右尖括号 (>>) 在特定情况下生成语法错误
- ADL在特定情况下不起作用
- C++11 在特定情况下避免冗余返回类型
- 在特定情况下跳出循环
- 子进程中的Execl仅在特定情况下工作
- 为什么boost asio async_read_some在特定情况下不调用回调