2014-10-11 2 views
0

파일을 읽은 다음 인쇄하려하지만 루프가 끝나지 않습니다. 왜??파일의 값 읽기 및 인쇄

char d; 
char code2 [12]={0}; 
string file1; 
cout<<"Input file name"<<endl; 
cin>>file1; 
string file2; 
cout<<"Input file name"<<endl; 
cin>>file2; 

ifstream input; 
input.open(file1.c_str()); 
ofstream output; 
output.open(file2.c_str()); 

while(! input.eof()) 
    { 
     int i=0; 
     while(d != ',' && i < sizeof(code2)) 
     { 
      input>>d; 
      code2[i]=d; 
      i++; 
     } 
     file2<<code2; 
    } 

디버깅하는 동안, 나는 CODE2의 쓰레기 값을 얻고있다 :

내 파일이 내 입력 등

66,67,256,258,69,73, 

로 한 줄이 포함되어 있습니다. 따라서 루프는 while의 끝에서 끝나지 않습니다.

+0

'eof'를 사용하지 마십시오. 이 주제에 관해서는 많은 질문과 답변이 있습니다. 수색. –

+0

읽기 _ [iostream :: eof가 루프 상태에있는 이유는 무엇입니까?] (http://stackoverflow.com/q/5605125/1870232) _ – P0W

+0

'd == ','' 중첩 된 루프의 최상단 (힌트 : 어떻게'input '이 eof에 도달 할 것인가?). – 0x499602D2

답변

2

eof()을 잘못 사용하여 초기화하기 전에 d을 사용하고 있습니다. 다음과 같이 좀 더 시도해보십시오.

char d; 
char code2 [13]={0}; 
string file1; 
cout<<"Input file name"<<endl; 
cin>>file1; 
string file2; 
cout<<"Input file name"<<endl; 
cin>>file2; 

ifstream input; 
input.open(file1.c_str()); 
ofstream output; 
output.open(file2.c_str()); 

int i = 0; 
while(input >> d) 
    { 
    if ((d == ',') || (i == 12)) 
     { 
     code2[i] = 0; 
     file2<<code2; 
     i = 0; 
     } 
    code2[i] = d; 
    i++; 
    } 

if (i > 0) 
    { 
    code2[i] = 0; 
    file2<<code2; 
    }