C ++我希望fscanf忽略换行符,但不忽略其他空格字符

时间:2018-11-06 10:06:53

标签: c++ file-io scanf newline

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

1 个答案:

答案 0 :(得分:0)

由于这应该是一个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;
    }
}