对于 cin 的操作 使用 getline(cin,str)往往可以实现更加简单以及安全的字符串操作,不同于 cin.getline(char*, int a),前者可以直接对字符串进行操作。
#include
#include
#include
usingnamespace std;
int main()
{
fstream iofile;
iofile.open("D:\\t.txt", ios::out| ios::in| ios::trunc);
string bookname;
string bookwriter;
cout <<"input the bookname:"<< endl;
getline(cin, bookname);
iofile << bookname << endl;
cout <<"input the bookwriter:"<< endl;
getline(cin, bookwriter);
iofile << bookwriter << endl;
iofile.close();
cout <<"read the input file:"<< endl;
iofile.open("D:\\t.txt");
while(getline(iofile, bookname))
{
cout << bookname << endl;
}
system("pause");
return0;
}
程序输入输出结果:
input the bookname:
we are the world
input the bookwriter:
Tanks
read the input file:
we are the world
Tanks
请按任意键继续...