求助:将文件中的大写字母全部改为小写

kingzy615 2011-03-21 01:32:15
我想读入一个文件,将其中所有大写字母改为小写。我想用一个fstream 来完成读和写的操作。文件Sample.txt里的文本是:How Are You 我想把它改为 how are you

下面是我的代码:

char temp_char;
fstream temp_file("Sample.txt");
while(temp_file.good())
{
temp_file.get(temp_char);

if(65<=temp_char && temp_char<=90)
{
temp_file.putback(temp_char);
temp_file<<(temp_char+=32);
}
}


但是运行完后文件里的内容没有改变。但是我在debug的时候查看fstream的buffer的时候,发现里面是正确的how are you。不知为何,最后就是没写到文件里去。求各位大神指点迷津。

...全文
623 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
pzlatcpp 2011-03-22
  • 打赏
  • 举报
回复
istream& putback ( char c );
Put character back

Decrements the internal get pointer by one, and c becomes the character to be read at that position by the next input operation.
kingzy615 2011-03-21
  • 打赏
  • 举报
回复
呵呵,多谢大家的意见。不过我用fstream的目的就是为了能够边读边写。我刚试了,没有close,问题不大,我查了下,是fstream的desctructor会自动关闭文件。我刚才运行了2楼的代码,结果正确,但是我有个小问题,2楼的代码中,把读写指针往回拨的语句:
temp_file.seekp(-1,ios_base::cur);

能不能改为:
temp_file.putback(temp_char);

多谢各位了!
tomatobin 2011-03-21
  • 打赏
  • 举报
回复
真的是这样吗?
bss001 2011-03-21
  • 打赏
  • 举报
回复
不关闭文件是不能写进去的……都说对了,呵呵
yarpee 2011-03-21
  • 打赏
  • 举报
回复
1楼正解。没fclose是不会flush到disk上去的。
4楼的建议很好。
pengzhixi 2011-03-21
  • 打赏
  • 举报
回复
请全部读出来,修改好了之后再写进去。没可能说读一个判断一个修改一个然后马上写回去的
FBIq 2011-03-21
  • 打赏
  • 举报
回复
读写之前用fseekg定位一下


fstream temp_file("c:\\sample.txt");
int readPos, writePos;
if (temp_file)
readPos = writePos = temp_file.tellg();
else
return 0;

while(temp_file.good())
{
temp_file.seekg(readPos++, ios_base::beg);
temp_file.get(temp_char);

if(65<=temp_char && temp_char<=90)
{ temp_file.seekg(readPos-1, ios_base::beg);
temp_file<<(temp_char+=32);
}
}
pzlatcpp 2011-03-21
  • 打赏
  • 举报
回复
用下面的代码试试:

char temp_char;
fstream temp_file("Sample.txt",fstream::out|fstream::in);

while(temp_file.good())
{
temp_file.get(temp_char);
if(65<=temp_char && temp_char<=90)
{
temp_file.seekp(-1,ios_base::cur); //
temp_file.put(temp_char+=32);
temp_file.flush(); //
}
}
temp_file.close();
bdmh 2011-03-21
  • 打赏
  • 举报
回复
最后要close文件,否则写不进去

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧