[英]c++ reading undefined number of lines with eof()
我正在使用eof()處理問題。 使用
string name;
int number, n=0;
while(!in.eof())
{
in >> name >> number;
//part of code that puts into object array
n++;
}
對於我來說,這聽起來很正常,因為只要文件中沒有更多文本,它就可以正常工作。 但是我得到的n是4200317。當我查看數組條目時,我看到文件中的第一個ats和其他的0。
可能是什么問題,我應該如何解決? 也許有解決此閱讀問題的另一種方法(行數不確定)
正確的方法:
string name;
int number;
int n = 0;
while(in >> name >> number)
{
// The loop will only be entered if the name and number are correctly
// read from the input stream. If either fail then the state of the
// stream is set to bad and then the while loop will not be entered.
// This works because the result of the >> operator is the std::istream
// When an istream is used in a boolean context its is converted into
// a type that can be used in a boolean context using the isgood() to
// check its state. If the state is good it will be converted to an objet
// that can be considered to be true.
//part of code that puts into object array
n++;
}
為什么代碼失敗:
string name;
int number, n=0;
while(!in.eof())
{
// If you are on the last line of the file.
// This will read the last line. BUT it will not read past
// the end of file. So it will read the last line leaving no
// more data but it will NOT set the EOF flag.
// Thus it will reenter the loop one last time
// This last time it will fail to read any data and set the EOF flag
// But you are now in the loop so it will still processes all the
// commands that happen after this.
in >> name >> number;
// To prevent anything bad.
// You must check the state of the stream after using it:
if (!in)
{
break; // or fix as appropriate.
}
// Only do work if the read worked correctly.
n++;
}
in << name << number;
這看起來像寫作,而不是閱讀。 我錯了嗎?
int number, n = 0;
您沒有初始化n
,並且您似乎有一個錯字。
這可能會更正確
string name;
int number, n = 0;
while (in >> name && in >> number)
{
n++;
}
這種做法是不好的做法 。
請注意,這里的代碼與您的代碼存在細微的差別:代碼遇到eof
時結束,或者如果發現錯誤的行(例如, Hello World
),則無聲地循環了無數次(例如, Hello World
),當代碼遇到格式不正確的“元組”(名稱+數字)或文件結尾(或存在其他錯誤,例如在操作過程中斷開磁盤:-))。 如果要檢查文件是否正確讀取,則過while
可以檢查in.eof()
是否為true。 如果為true,則正確讀取了所有文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.