C ++:每次我读fstream我有1个额外的字符在结束 [英] C++: Everytime I read in by fstream I got 1 extra character at the end

查看:104
本文介绍了C ++:每次我读fstream我有1个额外的字符在结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



编辑:


$

每次我读fstream的时候,我得到了一个额外的字符, b $ b

  ifstream readfile(inputFile); 
ofstream writefile(outputFile);
char c;
while(!readfile.eof()){
readfile>> C;
// c = shiftChar(c,RIGHT,shift);
writefile<< C;
}
readfile.close();
writefile.close();


解决方案

这通常是由于文件结尾测试错误。您通常想要执行以下操作:

  while(infile>> variable)... 

或:

  while std :: getline(infile,whatever))... 

但不是:

  while(infile.good())... 

或:

  while(!infile.eof())... 

编辑:前两个读取,检查它是否失败,如果是,退出循环。后两个尝试读取,处理什么是读取,然后如果先前的尝试失败,则在下一个迭代上退出循环。



Edit2:要轻松地将一个文件复制到另一个文件,请考虑使用这样的文件:

  //打开文件:
ifstream readfile(inputFile);
ofstream writefile(outputFile);

//做拷贝:
writefile<< readfile.rdbuf();


Everytime I read in by fstream I got 1 extra character at the end, How can I avoid this?

EDIT:

ifstream readfile(inputFile);
ofstream writefile(outputFile);
char c;
while(!readfile.eof()){
      readfile >> c;
      //c = shiftChar(c, RIGHT, shift);
      writefile << c;
}
readfile.close();
writefile.close();

解决方案

This typically results from testing for the end of file incorrectly. You normally want to do something like:

while (infile>>variable) ...

or:

while (std::getline(infile, whatever)) ...

but NOT:

while (infile.good()) ...

or:

while (!infile.eof()) ...

Edit: The first two do a read, check whether it failed, and if so exit the loop. The latter two attempt a read, process what was "read", and then exit the loop on the next iteration if the previous attempt failed.

Edit2: to copy one file to another easily, consider using something like this:

// open the files:
ifstream readfile(inputFile);
ofstream writefile(outputFile);

// do the copy:
writefile << readfile.rdbuf();

这篇关于C ++:每次我读fstream我有1个额外的字符在结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆