[問題] open file的問題

看板C_and_CPP (C/C++)作者 (小草)時間12年前 (2013/10/03 23:04), 編輯推噓0(006)
留言6則, 2人參與, 最新討論串1/1
我遇到一個問題 一開始將檔案名稱直接給定 再開檔 都沒有問題 但在我把ifstream file("a.txt"); 改成現在註解掉的部分(讓使用者輸入名稱的方式時) 輸入正確檔名 會顯示File was open correctly! 但是... 後面的那行就完全不會執行 不曉得是哪裡出了問題 .. 我原本再想是不是像scanf 會有殘存的問題? 還是先宣告ifstream file; 而後使用ifstream file(filename_str.c_str());這邊出問題 但若不在上方宣告 而只寫loop內一行 ifstream file(filename_str.c_str()) 則下面會顯示file does not declared 在網路上找好久都沒人提到> < 不曉得有沒有人知道問題在哪裡呢? 謝謝 #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { int count=0; string filename,filename_str; //ifstream file; vector<string> v1; string input; int i=0; cin.clear(); ifstream file("a.txt"); /* while(1){ cin>>filename_str; ifstream file(filename_str.c_str()); if(file.is_open()){ cout<<"File was open correctly!"<<endl; break; } cout<<"File does not exist!"<<endl; cout<<"Please input the file name again."<<endl; } */ while(file>>input){ v1.push_back(input); i++; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.217.85

10/03 23:15, , 1F
你說「後面那一行完全不會執行」到底是指哪一行?
10/03 23:15, 1F

10/03 23:21, , 2F
while(file>>input){ 這之後都不會執行
10/03 23:21, 2F

10/03 23:21, , 3F
抱歉沒說清楚> <
10/03 23:21, 3F

10/03 23:21, , 4F
ifstream只宣告一次就好了,後面要開檔用file.open()
10/03 23:21, 4F

10/03 23:22, , 5F
while 有執行到啊, 你 trace 看看就知道了
10/03 23:22, 5F

10/03 23:57, , 6F
改用file.open()後解決了 謝謝:)
10/03 23:57, 6F
文章代碼(AID): #1IJOUPfR (C_and_CPP)
文章代碼(AID): #1IJOUPfR (C_and_CPP)