2016-09-16 67 views
-2

當我運行下面的程序時,爲什麼我必須輸入兩次數字?about while(!(cin >> x))

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int x; 
    int number; 

    cout << "Please enter a integer ." << endl; 
    cin >> number; 

    while (!(cin>>x)) 
    { 
     cout << "Invalid value !" << endl; 
     system("pause"); 
     return 0; 
    } 

    cout << "Your number is " << number << " ." << endl 
+1

爲什麼你有x和整數作爲變量? x ???的目的是什麼? – Raindrop7

回答

4

您使用

cin >> number; 

然後

while (!(cin>>x)) 

而這兩種閱讀的數字。

+0

如果cin >>編號失敗,沒有機會分配x。例如:如果用戶輸入一個字母到整數 – Raindrop7

1

你正在從用戶輸入兩次輸入,Ist輸入是數字變量,另一個是while循環中的x變量。while循環條件的意思是「從用戶獲取輸入,當用戶輸入一個整數,然後停止循環「。因此,第一次循環開始並賦值給x條件變爲false,循環後的行執行。並且在循環中也不使用return 0語句。要終止循環,C++使用break語句:)