C++ ifstream 错误检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13446593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ ifstream Error Checking
提问by slowmotionfred
I am new to C++ and want to add error checking to my code plus I want to make sure I'm using good coding practices. I read a line from an ASCII file into a string using:
我是 C++ 新手,想在我的代码中添加错误检查,另外我想确保我使用了良好的编码实践。我使用以下命令将 ASCII 文件中的一行读入字符串:
ifstream paramFile;
string tmp;
//open input file
tmp.clear();
paramFile >> tmp;
//parse tmp
How can I error check to make sure the input file read was successful?
I'm seeing much more complicated ways of reading from an ASCII file out there. Is the way I'm doing it "safe/robust"?
如何进行错误检查以确保输入文件读取成功?
我看到了从 ASCII 文件中读取的更复杂的方法。我这样做的方式是否“安全/稳健”?
采纳答案by Jesse Good
paramFile >> tmp;
If the line contains spaces, this will not read the whole line. If you want that use std::getline(paramFile, tmp);
which reads up until the newline. Basic error checking is done by examining the return values. For example:
paramFile >> tmp;
如果该行包含空格,则不会读取整行。如果你想使用std::getline(paramFile, tmp);
它读取到换行符。基本的错误检查是通过检查返回值来完成的。例如:
if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
{
std::cout << "Successful!";
}
else
{
std::cout << "fail";
}
operator>>
and std::getline
both return a reference to the stream. The stream evaluates to a boolean value which you can check after the read operation. The above example will only evaluate to true if the read was successful.
operator>>
并且std::getline
都返回对流的引用。流评估为一个布尔值,您可以在读取操作后检查该值。如果读取成功,上面的示例只会评估为 true。
Here is an example of how I might make your code:
这是我如何制作您的代码的示例:
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
}