सेट किए बिना getline() का उपयोग करें सेट किए बिना वैध फ़ाइल पढ़ने के लिए getline()
का उपयोग करना संभव है? मैं failbit
का उपयोग करना चाहता हूं ताकि इनपुट फ़ाइल पठनीय न हो तो अपवाद उत्पन्न होता है।विफलता
निम्न कोड हमेशा अंतिम पंक्ति के रूप में basic_ios::clear
आउटपुट करता है - भले ही वैध इनपुट निर्दिष्ट किया गया हो।
test.cc:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream inf;
string line;
inf.exceptions(ifstream::failbit);
try {
inf.open(argv[1]);
while(getline(inf,line))
cout << line << endl;
inf.close();
} catch(ifstream::failure e) {
cout << e.what() << endl;
}
}
input.txt:
the first line
the second line
the last line
परिणाम:
$ ./a.out input.txt
the first line
the second line
the last line
basic_ios::clear
जब आप उम्मीद करते हैं जब getline का उपयोग कर failbit उठाया जा()? – selalerer
अगर फ़ाइल मौजूद नहीं है। उदाहरण के लिए './a.out nosuchfile.txt' – Jeremiah
इसके लिए आप फ़ाइल खोलने के बाद is_open() जांच सकते हैं। – selalerer