2013-04-29 60 views
1

我不能完全弄清楚爲什麼我的程序跳過了「cin.getline(staffMember,100);」。如果我添加一個像'q'這樣的分隔符,它會按預期工作。我不確定爲什麼它的行爲就像是自動輸入新行一樣。請有人請向我解釋爲什麼會發生這種情況?C++ cin.getline似乎被跳過了

#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <fstream> // Allow use of the ifstream and ofstream statements 
#include <cstdlib> // Allow use of the exit statement 

using namespace std; 

ifstream inStream; 
ofstream outStream; 

void showMenu(); 
void addStaffMember(); 

void showMenu() 
{ 
    int choice; 

    do 
    { 
     cout 
      << endl 
      << "Press 1 to Add a New Staff Member.\n" 
      << "Press 2 to Display a Staff Member.\n" 
      << "Press 3 to Delete a Staff Member.\n" 
      << "Press 4 to Display a Report of All Staff Members.\n" 
      << "Press 5 to Exit.\n" 
      << endl 
      << "Please select an option between 1 and 5: "; 

     cin >> choice; 

     switch(choice) 
     { 
      case 1: 
       addStaffMember(); 

       break; 
      case 2: 
       break; 
      case 3: 
       break; 
      case 4: 
       break; 
      case 5: 
       break; 
      default: 
       cout << "You did not select an option between 1 and 5. Please try again.\n"; 
     } 
    } while (choice != 5); 
} 

void addStaffMember() 
{ 
    char staffMember[100]; 

    cout << "Full Name: "; 

    cin.getline(staffMember, 100); 

    outStream.open("staffMembers.txt", ios::app); 
    if (outStream.fail()) 
    { 
     cout << "Unable to open staffMembers.txt.\n"; 
     exit(1); 
    } 

    outStream << endl << staffMember; 

    outStream.close(); 
} 

int main() 
{ 
    showMenu(); 

    return 0; 
} 

回答

4

當用戶輸入一個選項時,他們鍵入一個數字,然後按回車。這將包含\n字符的輸入放入輸入流中。當您執行cin >> choice時,將提取字符,直到找到\n,然後這些字符將被解釋爲int。但是,\n仍在流中。

後來,當您執行cin.getline(staffMember, 100)時,它會讀取到\n,並且看起來好像您在沒有實際鍵入任何內容的情況下輸入了新行。

爲了解決這個問題,通過使用ignore提取到下一個新行:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

這將提取的一切,直到幷包括未來\n字符並丟棄。所以實際上,當用戶輸入如1banana時,這甚至可以處理。 1將被cin >> choice提取,然後該行的其餘部分將被忽略。

0

在做cin >> choice;時,換行符由cin保留。所以當你接下來做getline時,它會讀到這個換行符並返回空(或空白)字符串。

0

使用

scanf("%d\n", &choice); 

或者您也可以使用後CIN >>選擇一個虛擬的getchar();

現在,跳過\n,正如一些答案中所解釋的。

0

cingetline()混合 - 儘量不要在相同的代碼中混用兩者。

請嘗試使用此代替嗎?

char aa[100]; 
// After using cin 
std::cin.ignore(1); 
cin.getline(aa, 100); 
//....