2012-03-30 130 views
0

由於我編碼了C++,並且我忘記了在收集字符串輸入時發生的惱人的事情,所以它已經有一段時間了。基本上,如果這個循環通過,比方說如果你使用負數,那麼它會跳過員工姓名行中的第二個循環。我記得之前有過這個問題,並且在輸入字符串之前或之後必須清除或執行此類操作。請幫忙!關於getline(cin,string)的C++快速問題

PS另外,任何人都可以幫助我以下正確的循環。我如何檢查字符串輸入中的值以確保它們輸入值?

#include <string> 
#include <iostream> 
#include "employee.h" 

using namespace std; 

int main(){ 

    string name; 
    int number; 
    int hiredate; 

    do{ 

     cout << "Please enter employee name: "; 
     getline(cin, name); 
     cout << "Please enter employee number: "; 
     cin >> number; 
     cout << "Please enter hire date: "; 
     cin >> hiredate; 

    }while(number <= 0 && hiredate <= 0 && name != ""); 

    cout << name << "\n"; 
    cout << number << "\n"; 
    cout << hiredate << "\n"; 

    system("pause"); 
    return 0; 
} 
+0

您只希望循環在名稱爲「」時停止?我想你想'name ==「」'?我想你也想用or('||')而不是和('&&') – GWW 2012-03-30 03:44:54

回答

1

你想改變你的循環條件是與否下面沒有設置任何。如果所有三個未設置,邏輯AND將僅觸發。

do { 
    ... 
} while(number <= 0 || hiredate <= 0 || name == ""); 

接下來,使用cin.ignore()通過@vidit規定獲得與閱讀在換行符擺脫問題。

最後,重要的是,如果您輸入整數的字母字符而不是整數,您的程序將運行無限循環。要緩解這種情況,請使用<cctype>庫中的isdigit(ch)

cout << "Please enter employee number: "; 
cin >> number; 
if(!isdigit(number)) { 
    break; // Or handle this issue another way. This gets out of the loop entirely. 
} 
cin.ignore(); 
+0

謝謝,先生!這應該適合我! – chadpeppers 2012-03-30 14:34:06

1

cin離開流,這會導致下一個CIN消費它在一個換行字符(\n)。有很多方法可以解決這個問題。這是一個方式..使用ignore()

cout << "Please enter employee name: "; 
getline(cin, name); 
cout << "Please enter employee number: "; 
cin >> number; 
cin.ignore();   //Ignores a newline character 
cout << "Please enter hire date: "; 
cin >> hiredate; 
cin.ignore()   //Ignores a newline character 
+0

好,但是如果你輸入一個字符而不是數字的整數,它不能解決問題,也不能解決如果你沒有輸入任何名稱,則循環。 – Makoto 2012-03-30 03:49:33