2012-04-11 2 views
1

먼저, 도움을 요청하십시오. 이 문제는 나를 괴롭 히고 있습니다.C++ : 새로운 C 문자열 입력을 허용하지 않습니다.

나는 c-string을 받아들이고 모음과 자음의 수를 셀 수있는 프로그램을 가지고있다. 이 문제없이 작동합니다. 그러나 사용자가 새 문자열을 만들 수있는 함수를 포함해야합니다. 그러나 사용자가 메뉴에서 "새 문자열"을 선택하면 사용자의 입력을 기다리지 않고 newString() 메서드를 반복합니다. 그런 다음 새 빈 화면을 만듭니다.

다음은 전체 프로그램입니다. newString() 방법은 끝입니다.

#include <iostream>  
using namespace std; 

// function prototype 
void printmenu(void); 
int vowelCount(char *); 
int consCount(char *); 
int cons_and_vowelCount(char *); 
void newString(char *, const int); 

int main() { 

    const int LENGTH = 101; 
    char input_string[LENGTH];  //user defined string 
    char choice;      //user menu choice 
    bool not_done = true;  //loop control flag 

    // create the input_string object 
    cout << "Enter a string of no more than " << LENGTH-1 << " characters:\n"; 
    cin.getline(input_string, LENGTH); 

    do { 
     printmenu(); 
     cin >> choice; 
     switch(choice) 
     { 
      case 'a': 
      case 'A': 
       vowelCount(input_string); 
       break; 
      case 'b': 
      case 'B': 
       consCount(input_string); 
       break; 
      case 'c': 
      case 'C': 
       cons_and_vowelCount(input_string); 
       break; 
      case 'd': 
      case 'D': 
       newString(input_string, LENGTH); 
       break; 
      case 'e': 
      case 'E': 
       exit(0); 
      default: 
       cout << endl << "Error: '" << choice << "' is an invalid selection" << endl; 
       break; 
     } //close switch 
    } //close do 

while (not_done); 
return 0; 
} // close main 

/* Function printmenu() 
* Input: 
* none 
* Process: 
* Prints the menu of query choices 
* Output: 
* Prints the menu of query choices 
*/ 
void printmenu(void) 
{ 
    cout << endl << endl; 
    cout << "A) Count the number of vowels in the string" << endl; 
    cout << "B) Count the number of consonants in the string" << endl; 
    cout << "C) Count both the vowels and consonants in the string" << endl; 
    cout << "D) Enter another string" << endl; 
    cout << "E) Exit the program" << endl; 
    cout << endl << "Enter your selection: "; 
    return;  
} 

int vowelCount(char *str) { 
    char vowels[11] = "aeiouAEIOU"; 
    int vowel_count = 0; 

    for (int i = 0; i < strlen(str); i++) { 
     for (int j = 0; j < strlen(vowels); j++) { 
      if (str[i] == vowels[j]) { 
       vowel_count++; 
      } 
     } 
    } 
    cout << "String contains " << vowel_count << " vowels" << endl; 
    return vowel_count; 
} // close vowelCount 

int consCount(char *str) { 
    char cons[43] = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"; 
    int cons_count = 0; 

    for (int i = 0; i < strlen(str); i ++) { 
     for (int j = 0; j < strlen(cons); j++) { 
      if (str[i] == cons[j]) { 
       cons_count++; 
      } 
     } 
    } 
    cout << "String contains " << cons_count << " consonants" << endl; 
    return cons_count; 
} // close consCount 

int cons_and_vowelCount(char *str) { 
    int cons = consCount(str); 
    int vowels = vowelCount(str); 
    int total = cons + vowels; 

    cout << "The string contains a total of " << total << " vowels and " 
      "consonants" << endl; 
    return total; 
} 

void newString(char *str, int len) { 
    cout << "Enter a string of no more than " << len-1 << " characters:\n"; 
    cin.getline(str, len); 
    return; 
} 

답변

6

cin >> choice 문은 뒤에 오는 캐리지 리턴이 아닌 입력 한 문자 만 사용합니다. 따라서 후속 getline() 호출은 빈 행을 읽습니다. 한 가지 간단한 해결책은 cin >> choice 대신 getline()을 호출 한 다음 첫 번째 문자를 선택 사항으로 사용하는 것입니다.

알아두기 : while (not done)do { … } 바로 뒤에 나타나야하고 return 0은 중복됩니다. 또한 프로그램의 시작 부분에 내용을 반복하는 대신 newString을 호출해야합니다.

+1

또 다른 해결책은'cin >> choice' 다음에'cin.ignore()'를 호출하는 것인데, 이는 스트림에서 바이트를 떨어 뜨릴 것입니다. – jli

+0

@jli : 사용자가 어리석은 경우 문자 다음에 공백을 입력하거나 ('A'를 입력해야한다고 생각하는 경우) 덜 강력합니다. 그러나 나는 머리카락을 나눌거야. 당신의 옵션은 완벽하게 유효합니다. –

+0

네, 동의 할 수 있습니다. (심지어 CRLF가 덜 견고 해 질 것입니다.) – jli

3

cin >> choice은 입력 스트림에 개행을 남기므로 다음을 getline()이 소비하고 반환합니다. 여러 가지가 있습니다. 한 가지 방법은 cin.ignore()cin >> choice 바로 뒤에 사용하는 것입니다.

0

cin >> choice은 스트림에서 한 문자 만 소비합니다 (이미 언급했듯이). 당신은

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

cin>>choice 후 선택을 읽은 후 스트림에 오는 모든 문자를 무시하도록 추가해야합니다.

p.s. #include <limits>

관련 문제