[英]error about using ifstream in loop
我有一個非常簡單的代碼,它的功能是鍵入程序將從中讀取數據的文件名。 由於文件輸入錯誤,文件可能不正確,因此如果先前的名稱無效,控制台將繼續要求用戶輸入名稱。
問題是,雖然第一個do-while循環運行良好,但如果在第一個循環中第一次未正確輸入文件名,則程序將跳過第二個while循環。 但是,如果正確輸入文件名,則一切正常。
我不知道為什么程序會這樣。
感謝您的幫助和您的寶貴時間!
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string context;
int step=0,i=0;
ifstream fin;
do {
string filename;
cout << endl << "please type in the name of input file" << endl;
cin >> filename;
string filepath = "files/" + filename;
cout << filepath << endl;
fin.open( filepath.c_str() );
} while( !fin.is_open() );
while (getline(fin, context)){
cout << context << endl;
cout << "hello" << endl;
}
fin.close();
return 0;
}
我認為在第一次嘗試后,“鰭”的狀態可能會受到污染。 為什么不嘗試在調用fin.open()之前先調用fin.clear()。
您需要清除您的ifstream,它可能被先前的文件嘗試損壞。
從標准來看
27.8.1.10
void open(const char* s, ios_base::openmode mode = ios_base::out);
調用rdbuf()->open(s,mode|out)
。 如果該函數返回空指針,則調用setstate(failbit)。 311A
那么,這條筆記311a是什么?
311a成功打開不會更改錯誤狀態。
盡管注釋不是規范性的,但是如果rdbuf->open()
成功,則規范性文本完全沒有說明成功打開對錯誤狀態rdbuf->open()
。 該注釋澄清了此非聲明。
底線:你需要clear
在調用文件流的狀態位open
,當你重新調用open
后失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.