大家好,我正在为一个项目编写部分代码,但我被困在一件事上。如果这是优秀的编码员在某个时候自己弄清楚的事情(因为我想成为一名优秀的编码员,第五周使用 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;
意思是:读一个int,然后读一个string,最后读另一个int。根本不读取变量 colon
的值。
您可以尝试以下代码以查看其行为方式:
string sep = ":";
int a, b;
cin >> a >> sep >> b;
cout << a << endl;
cout << sep << endl;
cout << b << endl;
关于c++ - 为什么这个 'if' 语句循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7695061/