Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
How can i get a string with the '\n' ( Enter )?
for example, in the this code, just can read the one of lines and not more.
C++
#include <iostream>
#include <string>
int main(){
    string str;
    std::cin>> str;
}

or in other words, what is the solutions for getting the strings and characters?
Thanks.
Posted
Updated 21-May-12 10:48am
v2

While normally I'd agree with loctrice that using std::getline is a good idea, doing what you want is a real pain using std::getline across all types of streams. FREX windows consoles can only be put into a end of file state by entering a CTRL^Z at a new line while for files it can be anywhere and not always after a newline is entered as on the console.

So what can you do about it? Well rolling your own isn't too hard, especially if you use what's already in the C++ standard library.
C++
std::istream &read_line_with_newline( std::istream &str, std::string &line  )
{
    for( char next = 0; str && next != '\n'; )
    {
        str >> std::noskipws >> next;
        line += next;
    }

    return str;
}
It's a bit of a flashback to pre-C++ days when you'd use fgetchar to do this sort of thing. The noskipws manipulator means that when you're reading don't ignore whitepace, process them as ordinary characters.

Edited for English fail and again for a typo, anyone'd think it wasn't my mother tongue!
 
Share this answer
 
v4
Comments
loctrice 22-May-12 9:35am    
+5. I should have taken more time with my response. You're answer is so much better than mine :doh:
The code part you posted will not read a line, it will read to a space character. A valid option would be to use getline and change the delimiter. You could also put the getline in a while loop.


Here is a great reference and forums for c++ [^]
 
Share this answer
 
v2
Comments
smss IR 21-May-12 17:17pm    
can you take a sample for this?
Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900