首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

用>>从文件读入char型变量有关问题

2012-02-11 
用从文件读入char型变量问题#include iostream#include fstream#include stringusingnamespacestd

用>>从文件读入char型变量问题
#include <iostream>
#include <fstream>
#include <string>

using   namespace   std;
int   main()
{
  fstream   f( "a.txt ",ios::out|ios::in|ios::trunc);  
  string   s1= "abcd   1234\n ";
  cout < < "Begin:tellp= " < <f.tellp() < <endl < <endl;

//测试:
f < <s1;
cout < < "tellp= " < <f.tellp() < <endl < <endl;
f.seekg(0);
char   ch= '* ';
while(f)  
{cout < < "tellg= " < <f.tellg() < <endl;
  f> > ch;
  cout < < "ch= " < <ch < < "\t "
          < < "tellg= " < <f.tellg() < <endl;//为什么位置指针每次移动2而不是1?
}
                           
cout < < "End:tellg= " < <f.tellg() < <endl;

  f.close();
  return   0;}


程序结果:
is_open=true
f.fail=false
Begin:tellp=0

tellp=11

tellg=0
ch=a         tellg=2
tellg=2
ch=c         tellg=4
tellg=4
ch=1         tellg=7
tellg=7
ch=3         tellg=9
tellg=9
ch=3         tellg=-1
End:tellg=-1

怎么是跳的读入char型变量的,为什么没有读入字符 'b ', 'd ', '2 ', '4 '?


[解决办法]
windows和unix的差异。
gcc/g++最初是unixt上的编译器。
[解决办法]
把string s1= "abcd 1234\n ";
改为string s1= "abcd 1234 ";一切正常

◆文本文件在不同系统上有不同格式,比如Windows以\r\n为行的间隔,而Unix以\n为行的间隔。
◆以文本方式打开文件时,会进行控制字符的处理,控制字符一般在0x20以下,比如0x00作为文本文件的结束符号,0x07作为响铃……。因为Windows以\r\n为行的间隔,所以它会把\r\n转化为\n,而Unix以\n为行的间隔,所以\n仍然是\n。这样一来文本流中的位置和文件中的位置则不等同,在进行转化时,windows会对每个\n加上/减去1,即使它是unix格式的文件,而unix则不,即使它是windows格式的文件。
◆tellg其实是通过seek(0,cur)而来,由第二点可知,如果文件格式不对,那么位置就会错乱,tellg就错误地更改了指针位置。
-------------------------------------
引用自http://blog.vckbase.com/bruceteen/archive/2006/03/27/18761.html
[解决办法]
ios::binary方式操作吧,
就不会有这个字符标准不一样的问题了 ...

热点排行