2016-08-04 2 views
0

.txt 파일을이 프로그램의 struct 배열로 읽고 내용을 표시하려고합니다.
파일은 다음과 같습니다struct C++의 배열로 파일 읽기.

Smith Jack 60 45 98 
Harry Hisk 45 40 78 
Kay  Jacob 35.5 23 45 
Dos  hed 23 20 35 
Noa  Tom 55 12 32 
Joe  Peni 57 49 78 
Vin  San 25.6 23 65.5 
Jes  Dan 24.3 12 78 
Zi  Lee 56 49 99 
Angi  Dev 57 48 97 
Donald David 60 50 96 
Davis Lal 47 47 80 
Alvis Sen  56 46 85 
Jack Jill 45 45 75 
Messy Lionel 60 49 100 

코드 나 실행 해요 :

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 
int main(){ 
    const int SIZE=50; 
    int i; 
    struct Records { 
     string firstname; 
     string secondname; 
     float test1mark; 
     float midtestmark; 
     float annualmark; 
    }record[SIZE]; 

    ifstream in("Data.txt"); 

    if (!in){ 
    cerr << "File can't be opened! " << endl; 
    system("PAUSE"); 
    exit(1); 
    } 
    for (int i=0; i < SIZE; i++){ 
    in >> record[i].firstname >> record[i].secondname 
    >>record[i].test1mark >> record[i].midtestmark >> record[i].annualmark ; 
    } 
    for (int i=0;i< SIZE;i++) { 
     cout << record[i].firstname<<" "; 
     cout << record[i].secondname<<" "; 
     cout << record[i].test1mark<<" "; 
     cout << record[i].midtestmark << " "; 
     cout << record[i].annualmark << " "; 
    } 
return 0; 
} 

출력 내가 갖는 :

Smith Jack 60  45  98 
Harry Hisk 45  40  78 
Kay  Jacob 35.5 23  45 
Dos  hed  23  20  35  
Noa  Tom  55  12  32 
Joe  Peni 57  49  78 
Vin  San  25.6 23  65.5 
Jes  Dan  24.3 12  78 
Zi  Lee  56  49  99 
Angi Dev  57  48  97 
Donald David 60  50  96 
Davis Lal  47  47  80 
Alvis Sen  56  46  85 
Jack Jill 45  45  75 
Messy Lionel 60  49  100 
       nan  0  8.94237e-039 
       4.36192e-039 0  -2.3511e-038 
       0  0  -2.3511e-038 
       0  0  0 
       1.32253e-038 0  1.32251e-038 
       4.2039e-045  0  -2.11122e+037 
       1.32251e-038 0  3.21276e-039 
       1.4013e-045  0  -2.3511e-038 
       1.4013e-045  0  3.76158e-037 
       0  0  3.76158e-037 
       0  0  1.12104e-044 
       4.36195e-039 0  4.36194e-039 
       3.57331e-043 0  6.0615e-039 
       0  0  3.21276e-039 
       4.2039e-045  0  6.41272e-039 
       1.12104e-044 0  6.63812e-039 
       4.36205e-039 0  -2.75237e+038 
       0  0  6.59812e-039 
       6.63426e-039 0  1.4013e-045 
       0  0  6.47961e-039 
       3.21319e-039 0  3.21319e-039 
       6.59812e-039 0  3.21299e-039 
       8.40779e-045 2.24208e-044 6.01433e-039 
       6.6045e-039  0  2.54408e-029 
       0  0  6.6045e-039 
       0  0  6.43946e-039 
       5.88656e-039 0  -4.12495e+011 
       0  0  0 
       5.88656e-039 0  2.54408e-029 
       nan  nan  6.43029e-039 
       0  0  0 
       5.93823e-039 0  -4.12495e+011 
       0  0  0 
       5.93823e-039 0  5.74532e-044 
       nan  nan  5.93837e-039 

프로세스 0.05447 후 종료 반환 값이 0 인 초 0
프레스 계속할 열쇠. . .

누군가가 내게 무엇이 잘못되었는지 말해 줄 수 있습니까? 나는 포인터를 사용하여 시도했지만 더 악화되었다. -Beginner

+0

'에서

int i; 

가 (내가에게 값 int = 0; i가 크기를 <; 내가 ++)하는 것이 필요하지 않습니다 믿고 {'- 어떻게 할 읽을 50 개의 데이터 항목이 있다는 것을 알고 계십니까? – PaulMcKenzie

+0

@PaulMcKenzie 그것은 과제 질문이며 요구 사항입니다. –

+0

나는 수업 중에 있지 않아서, 나는 일반적으로 대답 할 수 밖에 없다. 집계 할 경우 50 개의 항목이 없으므로 루프는 15 번째 항목 이후 가비지 데이터를 읽습니다. 어쨌든 "읽기 루프"를 작성하지 마십시오.파일 끝까지 또는 미리 설정된 한도에 도달 할 때까지 * 어느 것이 든 먼저 오는 시간에 루프를 수행해야합니다. 너를 위해, eof가 먼저 왔지만 계속 반복했다. – PaulMcKenzie

답변

1

파일의 파일 크기는 15이므로 15 행의 데이터 만 읽을 수 있습니다. 변수 SIZE을 사용하여 읽어야 할 행 수를 제어합니다.

SIZE50입니다. 이 아니라15입니다. 파일 끝 부분을 읽으려고 할 때 입력은 이 아니며이 아니며 16 번째 행 행을 읽어야합니다. 따라서 인덱스 15 이후의 변수는 초기화되지 않습니다. 은 정의되지 않았고입니다.

파일의 줄 수를 50으로 늘리거나 SIZE15으로 변경하십시오.

+0

고마워요! 그게 전부 였어 :) –

+0

EOF가 설정된 스트림에서 추출하는 것이 UB가 아닙니다. 단지 입력이 발생하지 않습니다. UB가 초기화되지 않은 데이터를 cout에 삽입합니다. –

+0

@DavidThomas 완전히 사실 :) 감사합니다 – Rakete1111

0

@ Rackete1111의 다른 대답으로 너무 많은 항목을 지정했으며 데이터를 읽는 루프가 파일의 실제 항목 수를 초과했습니다.

이런 식으로 말하면, 읽기 루프를 올바르게 작성하는 한, 실제로 얼마나 많은 레코드를 과장하여 잘못 입력해도 공간이 낭비되지 않습니다. 우리가 한계까지 읽어들이는 while 루프가

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

using namespace std; 

int main(){ 
    const int SIZE=50; 
    int i; 
    struct Records { 
     string firstname; 
     string secondname; 
     float test1mark; 
     float midtestmark; 
     float annualmark; 
    }; 

    Records record[SIZE]; 

    ifstream in("Data.txt"); 

    int recCount = 0; // keep track of actual number of records 

    // loop until we reach the end of file, or until we hit SIZE records, 
    // whichever comes first 
    while (!in.eof() && recCount < SIZE) 
    { 
     in >> record[recCount].firstname >> record[recCount].secondname 
     >>record[recCount].test1mark >> record[recCount].midtestmark >> record[recCount].annualmark ; 
     ++recCount; 
    } 

    // now recCount == 15 if you have 15 items. 

Live Example

참고 : 다음은 50 개 항목 대신 15을 진술의 "실수"를 만든 경우에도 루프를 작성하는 방법입니다 (50)에 도달했거나 파일 끝에 도달했습니다.

+0

하지만 [동안 (! eof ...) 잘못 생각됩니다] (http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition- 잘못 생각한) @PaulMcKenzie –

-1

그리고 나는 우리가 처음

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 



ifstream in("Data.txt"); 
const int SIZE = 15; 
void debugPrint(); 
void loadData(); 

struct Records { 
    string firstname; 
    string secondname; 
    float test1mark; 
    float midtestmark; 
    float annualmark; 
}record[SIZE]; 

int main() 
    { 
    loadData(); 
    debugPrint(); 
    } 

void debugPrint() 
{ 
    for (int i = 0; i < SIZE; i++) 
    { 
     cout << record[i].firstname << " "; 
     cout << record[i].secondname << " "; 
     cout << record[i].test1mark << " "; 
     cout << record[i].midtestmark << " "; 
     cout << record[i].annualmark << " " <<endl;   
    } 
    system("PAUSE"); 
} 

void loadData() 
{ 
    for (int i = 0; i < SIZE; i++) 
    { 
     if (!in) 
     {            
      cerr << "File can't be opened! " << endl; 
      system("PAUSE"); 
     } 

     in >> record[i].firstname >> record[i].secondname 
     >> record[i].test1mark >> record[i].midtestmark >> record[i].annualmark; 
    } 
}