【问题标题】:fstream get(char*, int) how to operate empty line?fstream get(char*, int) 如何操作空行?
【发布时间】:2013-12-15 20:28:48
【问题描述】:

strfile.cpp 中的代码:

#include <fstream>
#include <iostream>
#include <assert.h>

#define SZ 100

using namespace std;

int main(){
char buf[SZ];
{
    ifstream in("strfile.cpp");
    assert(in);
    ofstream out("strfile.out");
    assert(out);
    int i = 1;

    while(!in.eof()){
        if(in.get(buf, SZ))
            int a = in.get();
        else{
            cout << buf << endl;
            out << i++ << ": " << buf << endl;
            continue;
        }
        cout << buf << endl;
        out << i++ << ": " << buf << endl;
    }
}
return 0;
}

我要操作所有文件 但在 strfile.out 中:

1: #include <fstream>
2: #include <iostream>
3: #include <assert.h>
4: ...(many empty line)

我知道 fstream.getline(char*, int) 这个函数可以管理它,但是我想知道如何做到这一点只需使用函数“fstream.get()”。

【问题讨论】:

  • “如何操作”是什么意思?你想忽略空行吗?您的代码是否在空行上失败?
  • 对不起我的英语不好..我是什么当有一个空行时,用行号输出它。
  • 如果你想复制一个文件并在每行或 100 个字符之后插入一个行号,以先发生者为准,它对我来说很好。您能更具体地说明您的问题吗?
  • @lanmezhe: 你想只在空行上输出行号吗?
  • @molbdnilo 我知道怎么做了,还是谢谢大家!

标签: c++ get fstream


【解决方案1】:

因为ifstream::get(char*,streamsize) 将在流中保留分隔符(在本例中为\n),所以您的调用永远不会进行,因此在调用程序看来,您在无休止地读取空白行。

相反,您需要确定是否有换行符在流中等待,并使用in.get()in.ignore(1) 移过它:

ifstream in("strfile.cpp");
ofstream out("strfile.out");

int i = 1;
out << i << ": ";

while (in.good()) {
    if (in.peek() == '\n') {
        // in.get(buf, SZ) won't read newlines
        in.get();
        out << endl << i++ << ": ";
    } else {
        in.get(buf, SZ);
        out << buf;      // we only output the buffer contents, no newline
    }
}

// output the hanging \n
out << endl;

in.close();
out.close();

【讨论】:

  • 谢谢,我知道 getline() 可以做到。我只想知道如何做到这一点只使用 get()。
  • 谢谢,它有效!我认为问题是当 get(buf,SZ) 读取空行时,程序出错了。对吗?
  • 发生的情况是,它会将\n 留在流中,重复调用get(buf, SZ) 在换行处停止,因此您永远不会进步。它实际上只是没有移动超过行尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多