2013-04-29 90 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); 
//....