帮忙看一下我写的函数

来源:百度知道 编辑:UC知道 时间:2024/05/23 20:04:51
int create()
{string s,name;
char fn='n';
cout<<"请输入文件名:"<<endl;
cin>>name;
ofstream outfile("name",ios::out);
while((fn=='n')||(fn=='N'))
{cout<<"输入一行文本:"<<endl;
cin>>s;
outfile<<s<<endl;
cout<<"结束输入吗? y or n ?"<<endl;
cin>>fn;
}
cout<<"文件建立成功!"<<endl;
return 0;
}

ofstream outfile("name",ios::out);如果这样就不能创建文件,但编译不出错。如果改成 ofstream outfile("f1.txt",ios::out);就能成功。
请问怎么实现从键盘上输入文件名?

还有为什么当我输入的文件内容中含有空格时,就会出错,运行时狂闪,怎么实现输入空格?
error C2664: '__thiscall std::basic_ofstream<char,struct std::char_traits<char> >::std::basic_ofstream<char,struct std::char_traits<char> >(const char *,int)' : cannot
convert parameter 1 from 'class std::basic_string<char,struct std::ch

第一个问题:
请问你是在 windows下运行的吧,好象windows下对文件的后缀要求比unix要
严格,所以要打开一个文件,创建一个文件都得有后缀名,在unix下就不同了

从键盘上输入文件名:
你在问题补充中的错误信息就是提示:ofstream outfile("name",ios::out); 这里的第一个参数应该是const char*, 不能用string替代const char*
你就这样改吧:ofstream outfile(name.c_str(), ios::out);当然你从键盘输入的文件名也要有后缀!
说明,你这里的name 是string对象,要转换成字符串,string类中提供了c_str()函数就是把
一个string类对象转换成 char* 型的字符串

关于输入含空格的文件内容
可以把cin>>s; 语句改成 getline(cin, s);

如下:
int create()
{string s,name;
char fn='n';
cout<<"请输入文件名:"<<endl;
cin>>name;
ofstream outfile(name.c_str(),ios::out); ///////
while((fn=='n')||(fn=='N'))
{cout<<"输入一行文本:"<<endl;
getline(cin, s); ////////
outfile<<s<<endl;
cout<<"结束输入吗? y or n ?"<<endl;
cin>>fn;
}
cout<<"文件建立成功!"<<endl;
retu