[問題] run-time input string as file name

看板C_and_CPP作者 (君詠)時間13年前 (2011/03/12 13:23), 編輯推噓1(1010)
留言11則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Dev-C++ 問題(Question): 開啟程式之後輸入檔名 開啟該檔案 餵入的資料(Input): filename.csv 預期的正確結果(Expected Output): 看到filename.csv 錯誤結果(Wrong Output): 無法開啟該檔案 file open error // 自訂的 error message 程式碼(Code):(請善用置底文網頁, 記得排版) #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; int main() { string inputName; cout << "input fileName with extension\n? "; cin >> inputName; fstream ioFile( inputName.c_str(), ios::in | ios::out ); if( !ioFile ) { cerr << "file open error" << endl; system("pause"); exit(1); } system("pause"); return 0; } inputName.c_str() 是爬文時看到的 但好像沒有用... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.213.175

03/12 13:38, , 1F
!ioFile 請問這個是什麼
03/12 13:38, 1F

03/12 13:40, , 2F
if( !ioFile.is_open() ) 這樣不知道可不可以
03/12 13:40, 2F

03/12 13:54, , 3F
是 fstream 的 overloaded operator (開成功?true:false)
03/12 13:54, 3F

03/12 14:21, , 4F
我用Dev-C++執行沒問題,你會不會是檔案放錯位置了?
03/12 14:21, 4F

03/12 15:02, , 5F
我可以執行,但是一樣 file open error
03/12 15:02, 5F

03/12 15:17, , 6F
我的意思是你的csv檔可能放錯位置,所以才會讀不到檔。
03/12 15:17, 6F

03/12 15:25, , 7F
檔案沒特別指定路徑的話應該要跟cpp檔同資料夾
03/12 15:25, 7F

03/12 15:27, , 8F
可是如果那個檔案不存在路徑中, 應該會創造一個?
03/12 15:27, 8F

03/12 15:48, , 9F
會創造檔案的情況應該僅限於寫檔的時候吧?
03/12 15:48, 9F

03/12 15:51, , 10F
也就是把ios::in刪掉,只留下ios::out
03/12 15:51, 10F

03/12 15:52, , 11F
可以了,感謝樓上大大!
03/12 15:52, 11F
文章代碼(AID): #1DUmDS92 (C_and_CPP)