2017-07-22 88 views
-1

代碼如下。我想讓它在輸入-1時退出循環。或者我想找到一個更好的解決方案,如果有的話。爲什麼我的for循環不工作?

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]; 
    } 
} 
+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]; 
    } 
} 
+0

謝謝,但我不想讓我的程序退出只是跳回主要說話。 – midcore

+0

@midcore所有的'break'都會停止循環。如果後面有代碼,你的程序不會退出。 – stybl

+0

啊好的非常感謝你! :) – midcore