C ++ ifstream错误检查 [英] C++ ifstream Error Checking

查看:584
本文介绍了C ++ ifstream错误检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,想要添加错误检查我的代码,我想确保我使用良好的编码实践。我从一个ASCII文件中读取一行到一个字符串使用:

  ifstream paramFile; 
string tmp;

//打开输入文件

tmp.clear();

paramFile>> tmp;

// parse tmp




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


  2. 我看到从ASCII文件读取更复杂的方式。



解决方案

paramFile>> tmp; 如果行包含空格,这将不会读取整行。如果你想要使用 std :: getline(paramFile,tmp); 它一直读到换行符。通过检查返回值来完成基本错误检查。例如:

  if(paramFile>> tmp)//或if(std :: getline(paramFile,tmp)) 
{
std :: cout<< 成功!
}
else
{
std :: cout< 失败;
}

operator>> std :: getline 都返回对流的引用。流评估为一个布尔值,您可以在读取操作后检查。



下面是一个如何创建代码的例子:

  ifstream paramFile(somefile.txt); //使用构造函数而不是`open'
if(paramFile)//验证文件是否成功打开
{
string tmp; //构造一个保存行的字符串
while(std :: getline(paramFile,tmp))//按行读取文件
{
//读取成功,行
}
}
else
{
cerr<< 无法打开文件!\\\
; // Report error
cerr<< 错误代码:< strerror(errno); //获取有关为什么
}


的信息

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:

ifstream paramFile;
string tmp;

//open input file

tmp.clear();

paramFile >> tmp;

//parse tmp

  1. How can I error check to make sure the input file read was successful?

  2. I'm seeing much more complicated ways of reading from an ASCII file out there. Is the way I'm doing it "safe/robust"?

解决方案

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:

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.

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
}

这篇关于C ++ ifstream错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆