27

我是 C++ 新手,想在我的代码中添加错误检查,而且我想确保我使用了良好的编码实践。我使用以下命令将 ASCII 文件中的一行读入字符串:

ifstream paramFile;
string tmp;

//open input file

tmp.clear();

paramFile >> tmp;

//parse tmp
  1. 如何进行错误检查以确保输入文件读取成功?

  2. 我看到了从那里读取 ASCII 文件的更复杂的方法。我这样做的方式是“安全/稳健”吗?

4

1 回答 1

21

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
}
于 2012-11-19T01:58:04.970 回答