2

嘿伙计们,我正在为一个项目编写部分代码,但我被困在一件事上。如果这是一个优秀的程序员在某个时候自己想出来的事情(因为我想成为一个优秀的程序员,使用 c++ 的第五周;到目前为止一切都很好......)并且它是一个试验,说出这个词然后我'会搞砸的,但我已经调试了大约半个小时,不明白为什么我的“if”语句正在循环。

输入应如下所示:

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)
4

4 回答 4

2

这一行是错误的:

cin >> temp_start_hour >> colon >> temp_start_min;

含义:读取一个 int,然后读取一个字符串,最后读取另一个 int。变量的值colon根本不被读取。

您可以尝试以下代码以查看其行为方式:

string sep = ":";
int a, b;

cin >> a >> sep >> b;

cout << a << endl;
cout << sep << endl;
cout << b << endl;
于 2011-10-08T06:33:43.613 回答
1

您的第一个问题是“冒号”获取所有“:34”,然后 start_minutes 获取应该是下一小时的 12。但真正的问题是 cin 会在后续调用接收到的流中留下杂乱无章的内容,因此这些调用会跳过要求您提供更多输入,而只是使用剩余的字符。在每次调用后使用 cin.ignore() 作为一个笨拙的补丁来使其工作,但要更加努力地考虑使用更安全的功能重新设计整个事物。

于 2011-10-08T06:53:32.503 回答
0

问题在于变量的类型colon。修复非常简单:只需将colonfrom的类型更改stringchar

//string colon = ":"; //commenting out the old code
char colon; //new code : no need to initialize it

为什么string colon会导致问题,因为当类型是读取从一个字符开始的所有string字符直到遇到空格时,实际上,您打算只读取一个名为 的字符。为此,正确的数据类型是(或者您也可以选择)。cin':'':'charunsigned char

于 2011-10-08T09:22:15.460 回答
-1

你没有增加c变量

于 2011-10-08T05:57:26.667 回答