为什么我的for循环不起作用?

时间:2017-07-22 20:10:33

标签: c++ for-loop control-flow

代码如下。我希望它在您键入-1时退出循环。或者我想找到一个更好的解决方案,如果有的话。

if (aa == "hours") {
    std::cout << "Please enter hours below: (Type -1 to stop)" << std::endl;
    for(x; x > -1; x++) {
        std::cin >> hours[x];
        std::cout << hours[x];
    }
}

1 个答案:

答案 0 :(得分:0)

使用简单的break

if (aa == "hours") 
{
    int temp;
    std::cout << "Please enter hours below: (Type -1 to stop)" << std::endl;
    for(int x; x > -1; x++) {

        // Store input in temp
        std::cin >> temp;

        // Check if temp is -1
        if (temp == -1)
        {
            break;
        }

        // This code is only executed if temp is not -1
        hours[x] = temp;
        std::cout << hours[x];
    }
}