Streams, chars, and newlines

66 views Asked by At

I have something similar to

const char* a = "a\nb";
std::ostream data;

and I need to read "a" into "data". I tried using

data_stream << data;

but that stops at the line end, so only "a" is copied. Next I tried

while (data[0] != '\0')
{
    data_stream << data;
}

however this does not remove the line from the char, so it's an endless loop. What's the correct way to do this?

2

There are 2 answers

0
pang1567 On BEST ANSWER

use getline() get every line int the char *

0
striving_coder On

How exactly do you check that only "a" is copied? Can you present code and output for such check. The reason is, it should not happen: even if stream is flushed on "\n", it should still accept the following symbols ("b" in your example) after that.

Also your loop will indeed be infinite because you're checking for the first symbol every time, and it's naturally always not '\0' (since it's 'a'). What you probably intend to do is:

dp * char = data;  // creating pointer to char array
while (*dp)  // until the end of line is reached (at which point *dp evaluates to '/0' which is interpreted as false)
{
    data_stream << *dp++;  // outputting the char and moving pointer to the next one in array
}

And of course, as Captain Oblivious has pointed out, you need to get the names right in your second code piece.