FStream C++ automatic line addition

会有一股神秘感。 提交于 2019-12-08 07:27:40

问题


It is a pain to do an endline between each value with OFSTREAM. Here's an example of what I've got:

    ofstream fout("~/xample.txt");
    fout << val1;
    fout << endl;
    fout << val2;

I want to be able to do, instead,

    ofstream fout("xample.txt");
    fout << val1;
    fout << val2;

I don't care how the file is stored because I will write a configuration wizard anyways.


回答1:


If fout << val1 << endl; does not work with you, you might be able to inherit ofstream and create your own stream that adds endl automatically. But also you can drink water from fire hydrant.




回答2:


It is a pain ...

Besides you could simply write

fout << val1 << endl;
fout << val2 << endl;

you may use any other whitespace character value to delimit your values in the output file:

fout << val1 << ' ';
fout << val2 << ' ';
// ... more value outputs
fout << endl;

Shouldn't matter for the file size, but number of lines definitely.

UPDATE:
As you're asking how to extend the formatting behavior on std::ostream:
I don't think it's a good idea to use inheritance from std::streambuf, std::ostream, et al., and try to (re-)implement the interfaces themselves (as usually never it's a good idea inheriting STL classes, can be done though). I'd say the intended way is to use stream manipulators for such.

To automate appending the endl or any other delimiter you could write a small parameterized stream manipulator (at least this solution is copy/paste and IDE intellisense friendly):

template<typename T>
class auto_delim_manip
{
public:
    auto_delim_manip(T value_, char delim_) 
    : value(value_) 
    , delim(delim_) {}
    void put(std::ostream& os) const {
        os << value << delim;
        os.flush();
    }
private:
    T value;
    char delim;
};

template<typename T>
auto_delim_manip<T> auto_delim(T value, char delim = '\n') {
    return auto_delim_manip<T>(value,delim);
}

template<typename T>
std::ostream& operator<<(std::ostream& os, const auto_delim_manip<T>& autoDelim) 
{
    autoDelim.put(os);
    return os;
}

int main() {

    cout << auto_delim(5.2) << auto_delim(3) << auto_delim("Hello!");

    return 0;
}

Output:

5.2
3
Hello!

Check the running sample here.




回答3:


If you have a large number of values, simply put 'endl' on the same line as your output and loop through all of your data. Such as:

for(int i = 0; i < numValues; ++i) {
    fout << values[i] << endl;
}

I'm not aware of a built-in way to automate this, but it's honestly not that much work to add line endings manually.



来源:https://stackoverflow.com/questions/22263636/fstream-c-automatic-line-addition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!