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

标签 c++ loops if-statement while-loop do-while

大家好,我正在为一个项目编写部分代码,但我被困在一件事上。如果这是优秀的编码员在某个时候自己弄清楚的事情(因为我想成为一名优秀的编码员,第五周使用 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/

相关文章:

java - 初学者 Java 项目 : Basic Pokedex using if-else statements. 有建议吗?

c++ - 创建文件C++(Unix和Windows的跨平台解决方案)

java - 作为二项式的递归函数到迭代函数

php - while循环使用复选框php mysql仅插入最后一行

python - 在不使用列表、集合等的情况下在 Python 中生成唯一数字

PHP 循环 x 次,使用 while 和 if

excel - R 中的 IF 语句 - 始终嵌套?

c++ - C++模板方法中的循环依赖

c++ - 未定义模板的隐式实例化 'class'

c++ - 无法获取 std::mutex 来正确保护线程访问