簡體   English   中英

C ++中的文件讀取錯誤

[英]file reading error in C++

我有一個非常簡單的代碼,但是我無法找出錯誤。 任務:我想讀取包含浮點/雙精度值的文本文件。 文本文件如下所示:

--datalog.txt--

3.000315
3.000944
3.001572
3.002199
3.002829
3.003457
3.004085
3.004714
3.005342
3.005970
3.006599
3.007227
3.007855
3.008483
3.009112
3.009740
3.010368
3.010997

代碼看起來像這樣

--dummy_c ++。cpp--

#include <iostream>
#include <fstream>
#include <stdlib.h> //for exit()function
using namespace std;

int main()
{
  ifstream infile;
  double val;

  infile.open("datalog");

  for (int i=0; i<=20; i++)
    {
      if(infile >> val){
    cout << val << endl;
      } else {
    cout << "end of file" << endl;
      }
    }
  return 0;
}

輸出看起來像這樣:

end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file

正如我期望的那樣,它將打印與datalog.txt文件相同的內容。

你能幫我找出錯誤嗎?

謝謝,Milind。

如果您的文件確實名為datalog.txt ,則應確保嘗試打開該文件:

infile.open("datalog.txt");
//                  ^^^^^^

如果您沒有完全路徑,exe將在當前目錄中尋找它。

您指定的打開文件錯誤; 采用:

infile.open("datalog.txt");

您可以通過簡單的測試來防止嘗試使用未打開的文件:

infile.open("datalog.txt");
if (infile) {
    // Use the file
}

可能只是您拼寫錯誤的文件名嗎? 您說該文件名為“ datalog.txt”,但是在代碼中打開“ datalog”。

使用正確的文件名:-)然后,它對我有用。 “ datalog”文件只有18行,而不是20行。

如您所說,文件名為"datalog.txt" 在代碼中,您正在使用"datalog" 使用流之后,還請務必檢查流,以確保文件已正確打開:

int main()
{
    std::ifstream infile;
    double val;

    infile.open("dalatog.txt");

    if( infile )
    {
        for(unsigned int i = 0 ; i < 20 ; ++i)
        {
            if(infile >> val)
                std::cout << val << std::endl;
            else
                std::cout << "end of file" << std::endl;
        }
    }
    else
        std::cout << "The file was not correctly oppened" << std::endl;
}

另外,最好使用while循環而不是for循環來檢查EOF:

while( infile >> val )
{
    std::cout << val << std::endl;
}

也許使用std :: getline()函數會更好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM