C ++ fstream - 只读取某些变量类型的问题

时间:2014-02-11 16:13:51

标签: c++ fstream

我正在使用fstream读取包含数字数据的记事本文件。我正在使用动态内存分配,数据类型为float。 但是我的文件中有字符形式的胭脂数据 - 我如何编写搜索并忽略文件中字符的代码,只读取数字?

我假设我需要使用ignore或peek?

fstream myfile("data1");
myfile.ignore ();


or myfile.peek ();

但有点不确定。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:2)

如果它始终具有这种格式,则单词和数字由空格分隔,您可以一次只读取一个字符串并让std::istringstream进行解析。如果失败,您知道它不是数字

std::string word;
while (myfile >> word) {
    std::istringstream is(word);
    double d;
    if (is >> d) {
        // found a number
        std::cout << d << '\n';
    } else {
        // something's wrong
        std::cerr << word << '\n';
    }
}

更新

由于受欢迎的需求:stringstream的工作方式与其他任何流(std::cinstd::coutstd::fstream一样。主要区别在于stringstream对字符串进行操作。这意味着输入来自字符串而不是文件或标准输入,或输出转到字符串,就像它转到标准输出或文件一样。

答案 1 :(得分:0)

解析输入就像这样通常要求您将令牌提取到字符串中 根据您的解析要求测试字符串的内容。例如,当您提取到字符串中时,您可以运行一个函数,将其插入std::stringstream,然后提取到您要测试的数据类型,并查看它是否成功。

另一种选择是检查字符串是否某个字符串,如果是,则转换回所需的数据类型:

while (f >> str)
{
    if (f != "badInput")
    {
        // convert to double and add to array 
    }
}

幸运的是,您可以使用Boost.Regex设施来避免自己完成大部分工作。这是一个类似于你的例子:

#include <boost/regex.hpp>

int main()
{
    std::fstream f("test.txt");
    std::string token;

    boost::regex floatingPoint("((\\+|-)?[0-9]+)?(\\.)?([0-9]+)");

    while (f >> token)
    {
        if (boost::regex_match(token, floatingPoint))
        {
            // convert to double using lexical_cast<> and add to array
        }
    }

答案 2 :(得分:0)

感谢所有人的帮助 - 但对于我能力差的人来说,这一切看起来有点先进!我们建议使用以下内容 - 但我不确定如何区分单词和数字:

fstream myfile("data1");
myfile.eof ();
myfile.good ();
myfile.fail ();
myfile.clear ();
myfile.ignore ();
myfile.close ();
myfile.peek ();