为什么这个'if'语句循环?

Why is this 'if' statement looping?

本文关键字:循环 语句 if 为什么      更新时间:2023-10-16

嘿,伙计们,我正在为一个项目写一部分代码,我被一件事卡住了。如果这是优秀的程序员在某个时候自己发现的东西(就像我想成为一个优秀的程序员一样,第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变量