注册 登录
编程论坛 C++教室

[求助]file 输入 ,和输出 请大家帮忙

china008 发布于 2007-08-13 22:21, 524 次点击
谢谢各位网友,您要是知道希望帮个忙看看
这个代码的目的是从fileName.txt中读入文件名(例如: apple.txt)
然后, 打开文件apple.txt 读入其中的内容

#include"iostream" //注:尖括号
#include"string"
#include"fstream"
#include"cstdlib"
#include"Cstring"

using namespace std;

int main()
{
char a[50];
int i;
string b[3];
ifstream inFileName("fileName.txt", ios::in);

if(!inFileName)
{
cerr << "Can not open " << inFileName << endl;
system("pause");
exit( 1 );
}
i=0;
while( inFileName >> a)
{

b[i] = a;
cout << b[i] << endl;
i++;
}
cout << b[0];
ofstream outFileName( b[0], ios::out); //问题就在这,要是换成"apple.txt"
//就可以打开,可用b[0],就报错,可b[0]就是"apple.txt"呀?

if(!outFileName)
{
cerr << "Can not open " << inFileName << endl;
system("pause");
exit( 1 );
}

system("pause");
return 0;
}

p.s file.txt 中的内容: apple.txt
kivi.txt
grape.txt




5 回复
#2
terisevend2007-08-13 22:27
用 b[0].c_str( ) 就可以了...

[此贴子已经被作者于2007-8-13 22:30:27编辑过]

#3
china0082007-08-13 22:35
非常感谢占用您宝贵时间

您要是能稍微解释一下,就更感激不尽了.

#4
terisevend2007-08-13 22:39

b[0].c_str()
调用string类中的c_str()函数...可以把b[0]的转换成字符串并返回...
如果有错...请大家指正一下...

#5
aipb20072007-08-13 22:44
以下是引用terisevend在2007-8-13 22:39:41的发言:

b[0].c_str()
调用string类中的c_str()函数...可以把b[0]的转换成字符串并返回...
如果有错...请大家指正一下...

补充下,string是c++中标准库的字符串类型,用c_str();把这个类型转换为c风格字符串,也就是const char*型。
该用哪中类型要看具体的的型参要求,比如这里就该用c风格字符串。

#6
china0082007-08-13 22:46
非常感谢
1