为什么这个'if'语句循环?
Why is this 'if' statement looping?
嘿,伙计们,我正在为一个项目写一部分代码,我被一件事卡住了。如果这是优秀的程序员在某个时候自己发现的东西(就像我想成为一个优秀的程序员一样,第5周使用c++;到目前为止很好…),这是一个试验,说这个词,我会螺丝,但我已经在调试大约半小时,不明白为什么我的'if'语句是循环的。
输入应该像这样:
p 11:34 12:45
其中p表示是否完成(如果您想要输出,则为's',这里用'end'表示)。
const int LIST_SPACE = 1000; // this is outside of the main function
string c; // and is 1000 because of a parameter set by the teacher
string end = "s";
string start = "p";
int temp_start_hour;
int temp_start_min;
int temp_end_hour;
int temp_end_min;
string colon = ":";
int begin_hours[LIST_SPACE];
int begin_min[LIST_SPACE];
int end_hours[LIST_SPACE];
int end_min[LIST_SPACE];
int i = 0;
do {
cin >> c; //where c is a string
if(c != start && c != end)
{
cout << "ERROR IN INPUT";
return 1;
}
if(c != end)
{
cin >> temp_start_hour >> colon >> temp_start_min;
cin >> temp_end_hour >> colon >> temp_end_min;
begin_hours[i] = temp_start_hour;
begin_min[i] = temp_start_min;
end_hours[i] = temp_end_hour;
end_min[i] = temp_end_min;
cout << begin_hours[i]; //I did this to check if it was storing values
i++;
}
}while(c != end); //ending the do-while loop
我真的很感激你在正确的方向上轻推这家伙。或者是对我遗漏的概念的一般性建议。谢谢!
顺便说一下,我一直得到的输出是:(这是输入'p 11:34 12:34')11111111111111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111111111111
111111111111111111111Segmentation fault (core dumped)
这一行不对:
cin >> temp_start_hour >> colon >> temp_start_min;
含义:先读整型,再读字符串,最后再读另一个整型。不读取变量colon
的值
您可以尝试下面的代码来查看它的行为:
string sep = ":";
int a, b;
cin >> a >> sep >> b;
cout << a << endl;
cout << sep << endl;
cout << b << endl;
你的第一个问题是'冒号'得到所有的":34",然后start_minutes得到12,应该是下一个小时。但真正的问题是,cin在流上留下了被后续调用拾取的cruft,因此这些调用跳过要求您提供更多输入,而只接收剩余的字符。在每次调用之后使用cin.ignore()作为一个粗糙的补丁使其工作,但要用更安全的函数重新设计整个东西,需要付出更多的努力。
问题在于变量colon
的类型。修复非常简单:只需将colon
的类型从string
更改为char
:
//string colon = ":"; //commenting out the old code
char colon; //new code : no need to initialize it
为什么string colon
会导致问题,因为当类型为string
时,cin
读取从':'
开始的所有字符,直到遇到空格,而实际上,您只想读取一个名为':'
的字符。对于它,正确的数据类型是char
(或者您也可以选择unsigned char
)。
您没有增加c
变量
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如果 else 语句不断循环
- do while 循环中的 if 语句以 yes 或 no 结尾
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 如果语句不会在 do - while 循环中运行
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 什么可以用来替换代码中的循环和 if 语句?
- C++ 访问 if 语句(如果它们在 for 循环中)
- for 循环后的分号是什么意思?为什么第一个循环语句中有 j++
- 这段代码如何在没有任何循环语句或'goto'或递归的情况下循环?
- 终端不阅读循环语句
- 我的值不断增加,而不是在循环语句中重置
- 此 for 循环语句的正确语法
- 神秘的 for 循环语句
- do 循环语句导致无限循环
- 嵌套循环语句结果不正确
- 在 FOR 循环语句的条件部分中使用声明
- 构造长循环语句是一种好的做法吗
- 在条件C++循环语句中向SQLite3表中插入条目
- 循环语句警告的冒泡排序算法