2014-10-11 92 views
0

我正在尝试读取文件,然后将其打印出来,但循环未结束。为什么??读取和打印文件中的值

我的文件包含一行如

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

这是我输入:

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; 
    } 

调试时,我得到的代码2垃圾值。因此,循环不会在while结束时结束。

+0

不要使用'eof'。关于这个话题,有无数的问题和答案。搜索。 – 2014-10-11 16:35:23

+0

阅读_ [为什么iostream :: eof内部循环条件被认为是错误的?](http://stackoverflow.com/q/5605125/1870232)_ – P0W 2014-10-11 16:38:05

+0

考虑当'd ==',''从'嵌套循环的顶部(提示:“输入”应该如何达到eof?)。 – 0x499602D2 2014-10-11 16:39:35

回答

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; 
    }