slo*_*red 21 c++ error-handling ifstream
我是C++的新手,想要为我的代码添加错误检查,我想确保我使用良好的编码实践.我使用以下命令将ASCII文件中的一行读入字符串:
ifstream paramFile;
string tmp;
//open input file
tmp.clear();
paramFile >> tmp;
//parse tmp
Run Code Online (Sandbox Code Playgroud)
如何进行错误检查以确保输入文件读取成功?
我看到从那里读取ASCII文件的更复杂的方法.我这样做的方式是"安全/健壮"吗?
Jes*_*ood 13
paramFile >> tmp;如果该行包含空格,则不会读取整行.如果你想要那个std::getline(paramFile, tmp);读取直到换行的用法.通过检查返回值来完成基本错误检查.例如:
if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
{
std::cout << "Successful!";
}
else
{
std::cout << "fail";
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32938 次 |
| 最近记录: |