2015-11-04 29 views
0

我對於正在處理的初學者任務有一個疑問。初始作業要求我製作一個程序,要求用戶輸入除5之外的任何數字,直到用戶輸入5爲止。如果他們輸入5,程序將提醒他們輸入5。 下一部分任務需要我經過10次迭代或10次輸入非5值後,程序會向用戶發送消息並退出程序。 我完成了第一部分,但第二部分有問題。我搜索了stackoverflow並發現了一些關於「get」函數,但我不確定如何正確實現它。我將如何跟蹤輸入或迭代的次數,並且在程序退出n次成功迭代之後將其作爲條件?C++:在代碼中跟蹤迭代(在n次迭代後執行x)/用戶輸入

另外,如果用戶輸入一個字符而不是一個整數,程序會警告用戶並退出,我該如何制定一個條件?

感謝您的幫助。這是我迄今爲止編寫的代碼。

// This program works, however, if user inputs a character or a very large number 
//then the program malfunctions. 
// Learn more about the get function. 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int inpt; 

    cout << "Please input any number other than 5.\n"; 
    cin >> inpt; 

    while (inpt != 5) 
    { 
     cout << "Please input another number other than 5.\n"; 
     cin >> inpt; 
    } 

    if (inpt = 5) 
     { 
      cout << "Hey! You weren't supposed to enter 5!"; 
     } 


    return 0; 
} 

回答

0

你需要添加一個計數器

int count = 0; 

增量它每次輪循環

cout << "Please input another number other than 5.\n"; 
    cin >> inpt; 
    count++; 

和停止,如果計數變得太大

if(count>10) break; 

你也可以改變你的情緒重刑

if(inpt = 5)沒有做你的想法,你的意思inpt == 5

+0

謝謝你的有用的建議。對於if(count> 10),我實際上是把if(count = 10)。我會調整我的代碼,看看它是否有效。 –

+0

**注意**如果你想說「x是否有值5?」您必須輸入x == 5而不是x = 5。即使在if語句中,x = 5意味着「將x的值更改爲5」 – pm100

+0

謝謝您解釋x = 5和x == 5之間的差異。 –