新手向:简单的text输入输出

以前在VS中用惯了C语言的fopen,fscanf_s和fprintf_s,现在为了做一个文本查询和修改系统,开始使用输入输出流,也算是彻底走上了C++的道路。这里我倒是遇到几个问题

ifstream& open_file(ifstream &in,const string &file)//const  ifstream &in
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}



ofstream& open_file(ofstream &os,const string &file)const ofstream &os
{
os.close();
os.clear();
os.open(file.c_str());
return os;
}

输入输出流一定要清除状态,切记!此外不要习惯性的使用const限定词,因为输入输出流在运行的时候是会不断修改自身参数的!其次不要这样使用函数:

is = open_file(is, sfile);// 自身赋值会出错的!

bool read_file(ifstream &is, vector<string> &ivec)
{
if (NULL == is) 
{
cout << "No this file\n";
system("pause");
return false;
}

string temp;
while(!is.eof())
{
//is >> temp;
getline(is,temp);
//cout<<temp<<endl;
ivec.push_back(temp);
}
cout << "共有"<<ivec.size() << "行。"<<endl;
cout<<endl;
return true;
}


使用>>操作符是无法辨别空格的,如果要读取一行,最好的办法就是getline函数,而且支持string类,十分方便。


bool write_file(ofstream &os, vector<string> &ivec)
{
if (NULL == os)  //请记住在函数入口检查参数的有效性,另外如果流函数没有打开文件是不会报错的,直接变为NULL,所以要判断是否为空。
{
cout << "cannot write this file\n";
system("pause");
return false;
}


for (int i = 0; i != ivec.size(); ++i)
{
os << ivec[i];
os <<endl;
}
return true;
}


这里很糊涂的一点就是输入是用<<,还是输出用<<。反正只要记住如果向程序外部输出东西就是<<。


int _tmain(int argc, _TCHAR* argv[])
{
cout << "输入读取文件名称:\n";
string sfile;//file name 
vector<string> ivec;//text


getline(cin, sfile); //可以输入空格
if (sfile.empty()) 
{
sfile = string("D://testread.txt");//注意这里是两个/号哦
}
//cout << sfile <<endl;
ifstream is;
open_file(is, sfile);
if (read_file(is, ivec)) 
{
cout << "success!\n";
copy(ivec.begin(), ivec.end(), ostream_iterator<string>(cout, "\n"));
}

is.close();


//请记住一定要close,否则出错


cout << "输入 输出文件 名称:\n";
sfile.clear();
getline(cin, sfile); //可以输入空格
if (sfile.empty()) 
{
sfile = string("D://testwrite.txt");
}


ofstream os;
//os = open_file(os, sfile);
open_file(os, sfile);
if (write_file(os, ivec)) 
{
cout << "write successfully!\n";
}


os.close();




system("pause");
return 0;
}

你可能感兴趣的:(新手向:简单的text输入输出)