2013-04-29 2 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

사용자가 선택 항목을 입력하면 숫자를 입력 한 다음 Enter 키를 누릅니다. 이것은 입력 스트림에 \n 문자를 포함하는 입력을 넣습니다. cin >> choice을 수행하면 \n이 발견 될 때까지 문자가 추출되고 그 문자는 int으로 해석됩니다. 그러나 \n은 여전히 ​​스트림에 있습니다.

나중에 cin.getline(staffMember, 100)을 실행하면 \n까지 읽고 실제로 입력하지 않고 새 줄을 입력 한 것처럼 보입니다.

이 해결하기 ignore를 사용하여 다음의 새로운 라인까지 추출하려면

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

이 될 때까지 모든 것을 추출하고 다음 \n 문자를 포함하고 폐기됩니다. 사실, 사용자가 1banana과 같은 것을 입력 할 때도 처리됩니다. 1cin >> 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); 
//.... 
관련 문제