What's the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case?

后端 未结 8 1724
春和景丽
春和景丽 2020-12-02 04:48

When would I use std::istringstream, std::ostringstream and std::stringstream and why shouldn\'t I just use std::stringstream

8条回答
  •  执笔经年
    2020-12-02 05:29

    A stringstream is somewhat larger, and might have slightly lower performance -- multiple inheritance can require an adjustment to the vtable pointer. The main difference is (at least in theory) better expressing your intent, and preventing you from accidentally using >> where you intended << (or vice versa). OTOH, the difference is sufficiently small that especially for quick bits of demonstration code and such, I'm lazy and just use stringstream. I can't quite remember the last time I accidentally used << when I intended >>, so to me that bit of safety seems mostly theoretical (especially since if you do make such a mistake, it'll almost always be really obvious almost immediately).

    Nothing at all wrong with just using a string, as long as it accomplishes what you want. If you're just putting strings together, it's easy and works fine. If you want to format other kinds of data though, a stringstream will support that, and a string mostly won't.

提交回复
热议问题