2009-07-19 7 views
2

열거 형이 일반적으로 사용자 입력에 사용되는지 궁금합니다. 내 책 클래스에서 소설, 비소설 등 다양한 장르 열거자를 사용하여 열거 형 장르를 만들어야하는 연습을하고 있습니다.열거 형 및 사용자 입력

사용자가 프로그램을 사용하면 저장되는 책에 대한 정보. 장르의 경우 일반적으로 문자열 함수를 사용하여이를 수행하고 if 문으로 특정 이름으로 제한합니다.

그러나 열거 형과 동일한 프로세스를 수행하는 방법을 잘 모르겠다. 그런 식으로 사용하기로되어 있는지도 모르겠다. 관심이 있다면 여기에 코드가 있습니다. 이 기능들은 아직 완전히 구현되지 않았습니다의 일부이기 때문에 몇 가지 순간에 사용하지 않는

#include "std_lib_facilities.h" 

//Classes----------------------------------------------------------------------- 

class Book{ 
public: 
     Book(){}; // default constructor 
     //operators 
     friend ostream& operator<<(ostream& out, const Book& val); 
     bool Book::operator==(const Book& check) 
     //enumerators 
     enum Genre{ 
      fiction, nonfiction, periodical, biography, children}; 
     //member functions 
     string title(); 
     string author(); 
     int copyright(); 
     void ISBN(); 
     bool checkout(); 
private: 
     string title_; 
     string author_; 
     int copyright_; 
     int ISBN1; 
     int ISBN2; 
     int ISBN3; 
     char ISBN4; 
     bool checkout_; 
}; 

// Error Function--------------------------------------------------------------- 

void _error(const string& s) 
{ 
    cout << endl; 
    cout << "Error: " << s << endl; 
    cout << endl; 
} 

// Member Functions------------------------------------------------------------- 

string Book::title() 
{ 
     cout << "Title: "; 
     getline(cin,title_); 
     cout << endl; 
     return title_; 
} 

string Book::author() 
{ 
     cout << "Author: "; 
     getline(cin,author_); 
     cout << endl; 
     return author_; 
} 

int Book::copyright() 
{ 
    cout << "Copyright: "; 
    cin >> copyright_; 
    cout << endl; 
    return copyright_; 
} 

void Book::ISBN() 
{ 
    cout << "ISBN (Use spaces): "; 
    cin >> ISBN1 >> ISBN2 >> ISBN3 >> ISBN4; 
    if((ISBN1<0) || (ISBN2<0) || (ISBN3<0) || (ISBN1>9) || (ISBN2>9) || (ISBN3)>9) 
       _error("Must be single digit."); 
    else if(!isdigit(ISBN4) && !isalpha(ISBN4)) 
       _error("Must be single digit or letter."); 
    else{ cout << endl; 
      return;} 
} 

bool Book::checkout() 
{ 
    char check; 
    cout << "Checked out?(Y or N): "; 
    cin >> check; 
    switch(check){ 
    case 'Y': 
      cout << endl; 
      return true; 
      break; 
    case 'N': 
      cout << endl; 
      return false; 
      break; 
    default: 
       _error("Must be Y or N.");} 
} 

// Operator Overloads----------------------------------------------------------- 

ostream& operator<<(ostream& out, const Book& val){ 
     out << "Title: " << val.title_ << endl; 
     out << "Author: " << val.author_ << endl; 
     out << "ISBN: " << val.ISBN1 << "-" << val.ISBN2 << "-" << val.ISBN3 << "-" << val.ISBN4 << endl; 
     out << endl; 
     return out;} 

bool Book::operator==(const Book& check){ 
    return((ISBN1 == check.ISBN1) && (ISBN2 == check.ISBN2) && (ISBN3 == check.ISBN3) 
      && (ISBN4 == check.ISBN4));} 

// Main------------------------------------------------------------------------- 

int main() 
{ 
    bool finished = false; 
    char notfinished; 
    while(!finished) 
    { 
     Book book; 
     book.title(); 
     book.author(); 
     book.copyright(); 
     book.ISBN(); 
     book.checkout(); 
     cout << "Do you wish to store another book?(Y or N): "; 
     cin >> notfinished; 
     if(notfinished == 'Y'){ 
        cin.ignore(); 
        cout << endl;} 
     else if(notfinished == 'N') finished = true; 
     else _error("Must be Y or N"); 
     } 
    keep_window_open(); 
    } 

참고

(등, 책을 출력, 라이브러리에 저장) 그래서 가능하다면 나열된 열거 자에 대한 사용자 입력을 받아들이려면 어떻게 될까요? 장르 변수를 만드는 과정에서 뭔가를 생각하고있었습니다. 그런 다음 사용자가 cin >> variable을 입력하는 함수가 있습니다. 그러나 함수가 '허구'와 같은 입력을 이해하지 못하고 열거 자 값과 입력 만 수락한다고 생각합니다.

답변

0

C 스타일의 열거 형은 원래 문자열 이름을 복구 할 방법이 없기 때문에 이러한 목적으로 유용하지 않습니다. 일부 switch 기반 메커니즘을 만들 수도 있지만 그 시점에서 사용자가 직접 I/O 요구 사항을 충족시키는 방법을 설정할 수 있습니다.

+0

나는 그런 책 (장르 : 소설)로 통과 인수를 통해 프로그램에 직접 데이터를 저장한다면 그래서 그들은 단지 유용 할 것? – trikker

+0

예. 필자가 언급 한 스위치 기반 메커니즘의 일종은 'Genre :: whatever' 값으로 문자열을 앞뒤로 변환하는 것입니다. – chaos

+0

음 ... 알았어. 고마워. 만약 당신이 스위치를 기반으로하는 메커니즘의 의미에 대한 짧은 psuedo 코드 예제를 게시 할 수 있습니까? 나는 아직도 그것이 문자열로 어떻게 작동하는지 알지 못한다. – trikker

0

이 문제를 처리하는 방법 중 하나는 문자열의지도를 열거 형 값으로 설정하는 것입니다. 다른 가능성으로는 전용 기능이 있습니다.

일부 아이디어는 question을 참조하십시오.

This question에는 열거 형을 열로 변환하는 코드를 생성하는 방법에 대한 아이디어가 있지만 대부분의 예제는 역으로 작동합니다.

1

장르를 열거 형 (GenreTypeEnum)을 래핑하는 클래스로 만듭니다. 필요한 연산자를 추가하십시오. istream, ostream, 등호 연산자 등

istream 연산자에서 스트림에서 std :: string을 읽고 구문 분석하고 값을 연결된 GenreTypeEnum으로 변환 할 수 있습니다. 아마도 이런

뭔가 :

namespace GenreType { enum GenreTypeEnum { miscellaneous, fiction, non_fiction, children }; } 

    class Genre 
    { 
     public: 
     Genre() : genreType(GenreType::miscellaneous) {} 
     ~Genre() {} 

     void setType(std::string genreTypeString){ // implement string-> enum } 
     std::string toString(void) const { // convert genre back to string } 

     private: 

     GenreType::GenreTypeEnum genreType; 

    }; 

    std::ostream& operator<<(std::ostream& os, const Genre& genre) 
    { 
     os << genre.toString(); 
     return os; 
    } 

    std::istream& operator>>(std::istream& is, Genre& genre) 
    { 
     std::string input; 
     is >> input; 

     genre.setType(input); 
     return is; 
    }