2016-10-21 13 views
0

먼저, 내가 뭘 하려는지 설명하고 싶습니다. 그래서, 나는 그들의 이름 뒤에 10 개의 이름을 가진 텍스트 파일을 가지고있다. 구조를 만들고 함수 (void)를 사용하여 파일에서 정보를 읽으려고합니다. 그리고 내 코드 및 텍스트 파일입니다 :텍스트 파일에서 구조로 읽기

코드 :

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

using namespace std; 

void read(struct laLiga t[]) { 
    ifstream infile("info.txt"); 
    int i = 0; 
    while(infile >> t.team[i] >> t.points[i]) { 
     infile.get(t.team); 
     infile >> t.points; 
     i++; 
    } 
} 

struct laLiga { 
    char team[50]; 
    int points; 
}; 

int main() { 
    struct laLiga t[10]; 
    read(t); 
    return 0; 
} 

텍스트 파일 : 모든

Athletic Bilbao 15 
Atletico Madrid 18 
Barcelona 16 
Alaves 10 
Las Palmas 12 
Real Madrid 18 
Real Sociedad 10 
Sevilla 17 
Eibar 11 
Villarreal 16 
+0

귀하의 질문은 무엇입니까? – Michiel

답변

1

당신은 일을 더 쉽게하기 위해 std::vector을 사용할 수

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <sstream> 
#include <iomanip> 

using namespace std; 

auto file_text = 
R"(Athletic Bilbao 15 
Atletico Madrid 18 
Barcelona 16 
Alaves 10 
Las Palmas 12 
Real Madrid 18 
Real Sociedad 10 
Sevilla 17 
Eibar 11 
Villarreal 16)"; 

struct laLiga { 
    std::string team; 
    int points; 
}; 

void read(std::vector<laLiga>& t) { 
    //ifstream infile("info.txt"); // would also work 
    std::stringstream infile{file_text}; 
    while(infile) { 
     laLiga laliga{}; 
     std::string partial_team_name{}; 
     while(!(infile >> laliga.points)) { // keep going until we get the points 
      infile.clear(); // we could not read points, infile stream now in error; clearing to continue 
      if(infile >> partial_team_name) // maybe the next string is part of a team name 
       laliga.team += (laliga.team.empty() ? "" : " ") + partial_team_name; // add to team name with space if there was something already in there 
      else 
       return; // no points, no team, we're done 
     } 
     t.push_back(laliga); // after we get the points we can add the team 
    } 
} 

int main() { 
    std::vector<laLiga> t; 
    read(t); 
    for(auto i : t) { 
     std::cout << std::setw(30) << i.team; 
     std::cout << std::setw(10) << i.points << '\n'; 
    } 
    return 0; 
} 

출력 :

 Athletic Bilbao  15 
     Atletico Madrid  18 
      Barcelona  16 
       Alaves  10 
      Las Palmas  12 
      Real Madrid  18 
     Real Sociedad  10 
       Sevilla  17 
       Eibar  11 
      Villarreal  16 

live demo

+0

안녕하세요. 좋은 제안에 감사드립니다. 저는 벡터에 대해 이야기하고 있습니다. 모든 것이 좋아 보이지만 좀 더 설명이 필요합니다. 우선, 나는이 조건이 어떻게 작동하는지 이해하지 못한다 : "(infile >> laliga.points)". 둘째, 파일을 삭제해야하는 이유와 변경 내용을 이해할 수 없습니다. 마지막으로, 어떻게 작동하는지 설명해 주시겠습니까? 'laliga.team.empty()? "": "" '' '' ' –

+0

! (infile >> laliga.points)'는'infile'에서'points'까지 읽는 것을 의미합니다. 'infile >> laliga.points'가 실패하면'false'로 평가됩니다. 점을 읽을 수 없다면'! (infile >> laliga.points)'는'true'가되어 프로그램은 계속해서 팀 이름의 일부를 읽게됩니다. – wally

+0

'infile.clear();'는 플래그를 제외하고'infile'을 변경하지 않습니다. 플래그가 지워집니다. 'infile >> laliga.points'가 실패 (포인트를 읽을 수 없음) 한 후에 다시 읽으려고'infile'의 오류 플래그를 지워야합니다. – wally

3

첫째, 당신은 당신이 read에서 사용 전에 구조 를 정의해야 기능.

둘째로, 함수에서 변수가 t이고 배열이 아니라 구성원입니다. 따라서 t[i].teamt[i].points을 사용해야합니다.

셋째, 루프 상태의 >> 연산자를 사용하여 파일의 데이터를 이미 읽었습니다. 루프 안에서 을 다시 읽지 말아야합니다..

넷째로, 읽고 자하는 입력 파일은 생각보다 실제로 해석하기가 더 어렵습니다. 그 이유는 없이 공백이있는 이름을 둘 다 가질 수 있기 때문입니다. 입력 스트림의 get 기능과 입력 연산자 >> 둘 다 공백으로 구분됩니다. 아마도 read the whole line이어야하고 마지막 공간에서 분할해야합니다.

마지막으로 실제 대답 이유는 이 아니며은 실제로 질문을하지 않았거나 코드에 어떤 문제가 있는지 알려주지 않았습니다. 나중에 질문 할 경우 read about how to ask good questions을 입력하십시오.

+0

도와 주셔서 감사합니다. 질문을 올리기 전에 중요한 정보를 읽지 못해 죄송합니다. –

0

이 될 것이다 다음 가장 좋은 텍스트 파일에 구조체를 읽거나 쓸려면 ifstreamread() 기능을 사용하고 ofstreamwrite() 기능을 사용하십시오. 다음은 그것들을 사용하는 방법입니다.

#include <iostream> 
#include <fstream> 
#include <cstring> // for strncpy() 

using namespace std; 

struct laLiga { 
    char team[50]; 
    int points; 
}; 

int main() 
{ 
struct laLiga t; 

strncpy(t.team,"Some Name",sizeof("Some Name")); 
t.points = 100; 

//do this for writing a complete struct to a text file at once 
ofstream output("info.txt"); 
output.write(reinterpret_cast<char*>(&t),sizeof(t)); 
output.close(); 

//do this for reading a complete struct from a text file at once 

struct laLiga T; 

ifstream input("info.txt"); 
input.read(reinterpret_cast<char*>(&T),sizeof(T)); 
input.close(); 

//now T will hold both the name and points fields from the text file without doing it individually 

cout << "Name = " <<T.team << endl; 
cout << "Points = " << T.points << endl; 

return 0; 
} 

출력 (콘솔)

Name = Some Name 

    Points = 100 

모두 read()write() 함수의 첫 번째 매개 변수는 우리가 바이트의 순서로 전체 구조체를 캐스팅 한 후 파일에 쓸 reinterpret_cast를 사용하는 이유입니다 char*해야한다 . 이렇게하는 단점은 텍스트 파일이 일반 텍스트가 아니기 때문에 Windows에서 열 때 읽을 수 없지만 읽기 및 쓰기가 훨씬 쉽다는 것입니다.