how can I convert istream to string, when my istream also includes newline characters and I don't want to escape whitespaces? Thank you.
Asked
Active
Viewed 1,476 times
-3
-
Do you mean you want the string to contain the literal characters `'\'` and `'n'` instead of a newline? – Joseph Mansfield Apr 19 '15 at 18:00
-
Even just asking about "converting" a stream to a string suggests a fundamental misunderstanding. A stream is a flow of data, whereas a string is a container of bytes. The two are entirely different. Did you mean you wish to extract all bytes from the stream into a string, until the stream runs dry (reaches EOF)? Or what? Be specific and precise. – Lightness Races in Orbit Apr 19 '15 at 18:05
-
Unformatted input functions? `noskipws`? Initialize it with `istreambuf_iterator
`s? – chris Apr 19 '15 at 18:06
3 Answers
0
If you mean how to copy the whole std::istream
into a std::string
then there are many ways.
Here is one:
int main()
{
// here is your istream
std::ifstream ifs("test.txt");
// copy it to your string
std::string s;
for(char c; ifs.get(c); s += c) {}
// display
std::cout << s << '\n';
}
Galik
- 42,526
- 3
- 76
- 100
0
You can just allocate a string large enough for your whole file and read it at once:
ifstream fd(filename); // open your stream (here a file stream)
if (!fd)
exit(1);
fd.seekg(0, ios_base::end); // go to end of file
size_t filesize = fd.tellg(); // dtermine size to allocate
fd.seekg(0, ios_base::beg); // go to the begin of your file
string s; // create a new string
s.resize(filesize+1); // reserve enough space to read
fd.read(&s[0], filesize); // read all the file at one
size_t bytes_read = fd.gcount(); // it could be than less bytes are read
s.resize(bytes_read); // adapt size
Christophe
- 54,708
- 5
- 52
- 107
0
You can use a istreambuf_iterator
like
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream ifile("test.txt"); // open
std::string str(std::istreambuf_iterator<char>(ifile), {}); // initialize
std::cout << str; // display
}
vsoftco
- 52,188
- 7
- 109
- 221