[英]ifstream object.eof() not working
我認為我的while條件可能需要使用boolean bValue = false:
char cArray[ 100 ] = "";
ifstream object;
cout << "Enter full path name: ";
cin.getline( cArray, 100 );
if ( !object ) return -1 // Path is not valid? This statement executes why?
ifstream object.open( cArray, 100 );
// read the contents of a text file until we hit eof.
while ( !object.eof() )
{
// parse the file here
}
為什么我不能輸入文本文件的完整路徑名?
可能是由於事態的原因。 它們的語法是否為可以模擬eof的布爾語句?
我能有......嗎:
while ( !object == true )
{
// parase contents of file
}
請您和其他所有人注意,讀取文本文件的正確方法不需要使用eof(),good(),bad()或indifferent()函數(好的,我做了最后一個)。 在C中也是如此(使用fgets(),feof()等)。 基本上,只有在嘗試讀取某些內容之后,才使用getline()之類的函數來設置這些標志。 測試讀取函數(例如getline()實際上直接讀取某些東西)要簡單得多,而且更可能是正確的。
未測試-我正在升級我的編譯器:
#include <iostream>
#include <fstream>
#include <string>
using namespacr std;
imt main() {
string filename;
getline( cin, filename );
ifstream ifs( filename.c_str() );
if ( ! ifs.is_open() ) {
// error
}
string line;
while( getline( ifs, line ) ) {
// do something with line
}
}
ifstream::open
函數采用文件名和可選模式。 由於您想讀取整個文件,所以為什么不從頭開始:
ifstream obj(cArray);
if (obj) { // file successfully opened for reading
while (obj.good()) {
// read in a line at a time
string line;
getline(line, obj);
if (!line.empty()) { // we have something to work with
// parse
}
}
}
當然,更時尚的版本將像Neil Butterworth一樣在while
循環中測試getline
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.