作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [转录]想请问关於ifstream open file的问题...
时间Tue Dec 22 02:09:02 2009
※ 引述《ric2k1》之铭言:
: 标题: 想请问关於ifstream open file的问题...
: 时间: Mon Dec 21 23:56:52 2009
: 在作业六里面,readCir传入的参数是string&
: 但是ifstream 的open function的传入参数是char*
: 我稍微试了一下,发现 char* c = "blahblah"; string s = c; 这样写是可以的
: 但是相反过来就不行?? string s ="blahblah"; char* c = s; (compile error!!)
char* 是 pointer, 但是 string 是 class.
"string s = c" 会呼叫 string 的 constructor 将 "char* c" 传进去,
但是 char *c 不能随便 assign, 除非 RHS 也是 char *.
: 所以我在测试的时候readCir都传char*进去...
: 可是又发生其他问题,当我写 char* fileName = "C17.cir"; 传进readCir没有问题
: 但当我写 char* fileName; cin >> fileName; 再传进去就有问题了
You need to allocate memory for a pointer variable. In your case, fileName is
used without initialization, so it will definitely crash because ostream is
tring to writing something to "*fileName"...
: 程式会在测试用的main里面所有东西执行完之後最後发生"记忆体区段错误"的讯息
: ddd的错误讯息是segmentation fault,然後是停在 #include<string.h>前面...
: 不明白...这到底是为什麽呢??
Try:
1.
string fileName;
cin >> fileName;
ifstream ifile(fileName.c_str());
OR 2.
char fileName[1024]; // assume strlen(fileName) is < 1024... not good though
cin >> fileName;
ifstream ifile(fileName);
OR 3.
char *fileName = new char[1024];
cin >> fileName;
ifstream ifile(fileName);
delete [] fileName;
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.224.46.80