【问题标题】:C++ I want fscanf to ignore newline characters but not other whitespace charactersC ++我希望 fscanf 忽略换行符而不是其他空白字符
【发布时间】:2018-11-06 10:06:52
【问题描述】:

在我的程序中,我想逐个字符地从文件中读取数据并将它们存储在某处,但我想忽略换行符。我整天都在努力寻找解决方案。当我在 %c 之前留一个空格时,当我使用 fscanf(fp, "%*[\n]", ch); 之类的东西时,它会忽略所有空格,我无法让它从下一行继续阅读。或者由于某种原因它只读取最后一行。有人可以帮帮我吗?

【问题讨论】:

  • 您最好从输入中逐个字符地读取,随意拆分数据。也许您可以将过滤后的输入放在字符缓冲区中并从那里使用 sscanf() 以使您免于重新发明轮子,例如解析数字时。

标签: c++ file-io scanf newline


【解决方案1】:

既然这应该是一个 C++ 问题,那么 iostream/boost::...::filter_istream 解决方案怎么样?它为您提供了 iostream 的全部输入容量(数字解析等)

 #include <boost/iostreams/device/file.hpp>
 #include <boost/iostreams/filtering_stream.hpp>
 #include <boost/iostreams/concepts.hpp>

 #include <iostream>
 #include <fstream>

 static const int NL = 0xa;
 class nl_input_filter : public boost::iostreams::input_filter {
 public:
     template<typename Source>
     int get(Source& src) {
         int c;
         while ((c = boost::iostreams::get(src)) != EOF && c !=   boost::iostreams::WOULD_BLOCK) {
            if(c != NL)
                break;
        }
        return c;
    }
 };

 int main()
 {
     std::ifstream fi("/tmp/bla");
     boost::iostreams::filtering_istream in;
     std::string s;
     in.push(nl_input_filter());
     in.push(fi);
    while ( in >> s )
    {
        std::cerr << s << std::endl;
    }
}

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多