簡體   English   中英

C ++ ifstream錯誤檢查

[英]C++ ifstream Error Checking

我是C ++的新手,想要為我的代碼添加錯誤檢查,我想確保我使用良好的編碼實踐。 我使用以下命令將ASCII文件中的一行讀入字符串:

ifstream paramFile;
string tmp;

//open input file

tmp.clear();

paramFile >> tmp;

//parse tmp
  1. 如何進行錯誤檢查以確保輸入文件讀取成功?

  2. 我看到從那里讀取ASCII文件的更復雜的方法。 我這樣做的方式是“安全/健壯”嗎?

paramFile >> tmp; 如果該行包含空格,則不會讀取整行。 如果你想使用std::getline(paramFile, tmp); 讀取直到換行符。 通過檢查返回值來完成基本錯誤檢查。 例如:

if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
{
    std::cout << "Successful!";
}
else
{
    std::cout << "fail";
}

operator>>std::getline都返回對流的引用。 流評估為布爾值,您可以在讀取操作后檢查該值。 如果讀取成功,上面的示例將僅評估為true。

以下是我如何制作代碼的示例:

ifstream paramFile("somefile.txt"); // Use the constructor rather than `open`
if (paramFile) // Verify that the file was open successfully
{
    string tmp; // Construct a string to hold the line
    while(std::getline(paramFile, tmp)) // Read file line by line
    {
         // Read was successful so do something with the line
    }
}
else
{
     cerr << "File could not be opened!\n"; // Report error
     cerr << "Error code: " << strerror(errno); // Get some info as to why
}

暫無
暫無

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

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