C++读写文件乱码

源程序,很简单,将一个a写入文件再读出来显示:
#include<iostream>#include<fstream>
#include <string>
using namespace std;
int main()
{
string name="file.txt";
string incontent="a";
string outcontent;
cin.clear();
cout.clear();
fstream file_inout(name.c_str());

file_inout<<incontent; //write to file
file_inout>>outcontent; //read from file
cout<<(outcontent.c_str());
file_inout.close(); file_inout.clear();
system("pause");
return 0;
}
项目:

现在运行出现如下结果:

查看文件已经被修改(第一个对的,后面多了好多中文):

尝试只读出文件内容,预先写好文件时,能够正常读出并且显示的。新手学习,望高手指教。

#include<iostream>

#include<fstream>

#include <string>

#include<cstdlib>

 using namespace std;

 int main()

 {

  string name="file.txt";

  string incontent="a";

  string outcontent;

  cin.clear();

  cout.clear();


  ofstream file_in(name.c_str());

  file_in<<incontent;  //write to file

  file_in.close();


  ifstream file_out(name.c_str());

  if(!file_out)cout<<"fuck";

  file_out>>outcontent; //read from file

  cout<<outcontent;


  file_out.close();

  file_out.close();

  system("pause");

  return 0;

 }

//输入ifstream 和ofstream不一样

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-02-01
一般应该避免用一个fstream,读文件和写文件最好分开,读写之间关闭和打开stream。否则会出现难以预料的结果。
第2个回答  2013-02-01
你的读写是不对的,向文件中写入应该这样
ofstream fout("test.txt");
fout<<"a";
fout.close();
读取文件内容是这样的:
char s;
ifstream fin("test.txt");
fin>>s;
fin.close();
第3个回答  2021-03-31

securecrt乱码怎么办

第4个回答  2013-02-01
file_inout<<incontent; //write to file
file_inout>>outcontent; //read from file
输入输出用一个文件流 中间是否应该close 或 clear一下
相似回答