2014-06-20 3 views
0

ID, 책 이름, 작성자, 작성한 연도, 장르 등으로 구성된 책 목록이 파일에 있습니다. 나는파일에서 읽은 줄 분리하기 C++

(추출물)

1 The Da Vinci Code Dan Brown 2003 mistery-detective 20 3 
2 Think and Grow Rich Napoleon Hill 1937 non-fiction 50 5 
3 Harry Potter and the Half-Blood Prince J. K. Rowling 2005 fantasy 92 8 
4 The Catcher in the Rye J. D. Salinger 1951 novel 100 6 

하는 배열에게 정보를 구조체하는 올바른 방법의 f.e. Books.txt 파일에서 읽는 방법을 찾을 수 없습니다 Book_list [0] .id는 1, Book_list [0] .name = Da Vinci 코드 등이어야합니다. 아이디어는 각 정보 평화가 탭으로 구분된다는 것입니다. 나는 충분히 명확하지 않은 것을 묻는다면 미리 미안하다.

#include <iostream> 
#include <string> 
#include <fstream> 

struct Book 
{ 
    int id; 
    std::string name; 
    std::string author; 
    int year; 
    std::string genre; 
    int times_given; 
    int available; 
}; 

int main() 
{ 
    int book_list_size = 500; 
    int number_of_books = 0; 

    Book book_list[book_list_size]; 
    std::ifstream book_input_stream("Books.txt"); 

    std::string line; 

    while (std::getline(book_input_stream, line)) 
    { 
     ++number_of_books; 
    } 

    book_input_stream.close(); 
    book_input_stream.open("Books.txt"); 

    for (int i = 0; i < number_of_books; i++) 
    { 
     book_input_stream >> book_list[i].id >> book_list[i].name 
       >> book_list[i].author >> book_list[i].year 
       >> book_list[i].genre >> book_list[i].times_given 
       >> book_list[i].available; 
    } 

    for (int i = 0; i < number_of_books; i++) 
    { 
     std::cout << book_list[i].id << " " << book_list[i].name << " " 
       << book_list[i].author << " " << book_list[i].year << " " 
       << book_list[i].genre << " " << book_list[i].times_given << " " 
       << book_list[i].available << std::endl; 
    } 

    book_input_stream.close(); 

    return 0; 
} 
+1

특히이 답변을 확인하십시오 : http://stackoverflow.com/a/23070803/1413395 –

+0

이와 같은 파일이 제공 되었습니까, 아니면 파일을 만드시겠습니까? – aceBox

+0

텍스트 파일을 변경할 수 있다면 구분 기호를 사용하는 것이 가장 좋습니다 ...이 경우 다양한 필드를 구별 할 수 있습니다. – aceBox

답변

0

먼저 두 번 파일을 읽을 필요가 없습니다, 기본적으로 가변 길이 배열 std::vector이라는 놀라운 클래스가있다. 당신은 당신의 파일 및 쓰기의 상단에

#include <vector> 

을 추가 할 수 있습니다

std::vector<Book> book_list; 

목록을 만들 수 있습니다. 익숙한 방법으로 이미 추가 책을

book_list.push_back(Book()); 

및 액세스 : 그때부터 당신이 새 책을 추가 할 수 있습니다

book_list[0].id 

를 파일에서 읽기에 관해서는, >> 연산자는 공백까지를 읽고 탭이 모든 get* 기능의 공백을 건너 뛸 수 없습니다와 같은 물론

string s; 
getline(book_input_stream, s, '\t'); 

를 사용하는 경우에만에서 중지, 그래서 당신이 하나 개의 탭을 사용하여 만들거나 012을 사용을 클릭하면 공백을 추가로 건너 뛸 수 있습니다. 책을 읽을 수

한 가지 가능한 방법은 : 당신은 탭으로 구분 필드의 데이터 라인을,이 경우 일반 솔루션 각 라인 라인으로 라인을 읽고, 그리고 휴식 것이

Book b; 
book_input_stream >> b.id >> std::ws; 
getline(book_input_stream, b.name, '\t'); 
book_input_stream >> std::ws; 
getline(book_input_stream, b.author, '\t'); 
book_input_stream >> b.year >> std::ws; 
getline(book_input_stream, b.genre, '\t'); 
book_input_stream >> b.times_given >> b.available; 
book_list.push_back(b); 
0

그 다음에 마지막으로 을 변환해야하는 데이터로 변환하십시오. 그리고 Book에는 생성자가 이어야합니다. C++ 11에서는 아무 것도하지 않고도 할 수 있지만 생성자는 여전히 작업을보다 명확하게 만듭니다. 뭔가 같이 : 그 문제에 대한

std::vector<Book> books; 
std::string line; 
int lineNumber = 0; 
while (std::getline(input)) { 
    ++ lineNumber; 
    std::vector<std::string> fields(split(line, '\t')); 
    if (fields.size() != 7 /* || other validations */) { 
     // error handling... 
     // it's nice when the error messages contain the line number 
    } else { 
     books.push_back(
      Book(
       asInt(fields[0]), 
       fields[1], 
       fields[2], 
       asInt(fields[3]), 
       fields[4], 
       asInt(fields[5]), 
       asInt(fields[6]))); 
} 

, 당신은 (일반적으로한다) Book에 대한 >> 연산자를 정의 할 수 있습니다 :

std::istream& 
operator>>(std::istream& source, Book& dest) 
{ 
    std::string line; 
    std::getline(source, line); 
    if (source) { 
     std::vector<std::string> fields(split(line, '\t')); 
     if (fields.size() != 7 /* || other validations */) { 
      source.setstate(std::ios_base::failbit); 
     } else { 
      dest = Book(
        asInt(fields[0]), 
        fields[1], 
        fields[2], 
        asInt(fields[3]), 
        fields[4], 
        asInt(fields[5]), 
        asInt(fields[6])); 
    } 
    return source; 
} 

를 그리고, 당신이 할 필요가있다 :

std::vector<Book> books; 
Book book; 
while (input >> book) { 
    books.push_back(book); 
} 
관련 문제