Computer Science Canada Another string problem |
Author: | halo3d [ Sat Nov 11, 2006 10:45 pm ] |
Post subject: | Another string problem |
well i got another problem.. in this thing when user enters a long string like this is a string it comes out in the file like this is a string any way .. can u guys tell me how i can make it so that it stores the input into string variable only when user presses enter and not space... im uploading the whole project this time.. |
Author: | wtd [ Sat Nov 11, 2006 11:00 pm ] |
Post subject: | |
When you use the extraction operator to obtain a string from an input stream, it stops at the first whitespace. To read an entire line, you must use the std::getline function. |
Author: | bugzpodder [ Sun Nov 12, 2006 10:25 am ] |
Post subject: | |
don't forget to becareful when mixing cin with getline. see post named random string line |
Author: | wtd [ Sun Nov 12, 2006 10:56 am ] |
Post subject: | |
Could you explain what you mean about mixing cin and getline? I don't think I'm seeing the issue you are. |
Author: | halo3d [ Sun Nov 12, 2006 12:22 pm ] |
Post subject: | |
so how exactly do i use std::getline in my program here? i mean whats the syntax and stuff... any example? |
Author: | ericfourfour [ Sun Nov 12, 2006 1:38 pm ] | ||
Post subject: | |||
I would try
|
Author: | wtd [ Sun Nov 12, 2006 1:52 pm ] |
Post subject: | |
http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespacestd.html#a645 |
Author: | halo3d [ Sun Nov 12, 2006 2:02 pm ] | ||
Post subject: | |||
ericfourfour wrote: I would try
Why thanx ericfourfour i would use google from now rather than this site... thanx for the "little" help.. bye |
Author: | bugzpodder [ Mon Nov 13, 2006 10:09 pm ] | ||||||
Post subject: | |||||||
wtd wrote: Could you explain what you mean about mixing cin and getline? I don't think I'm seeing the issue you are.
cin>>x misses the newline char. getline chews everything including the newline char. Hence a getline after a cin will usually result in an empty string being fetched, most likely not the intended behaviour. I don't see how one could get around this without managing newlines explicitly and very carefully. Input
Output:
|
Author: | wtd [ Mon Nov 13, 2006 10:48 pm ] | ||
Post subject: | |||
This just calls for input validation. Maybe something like:
|
Author: | bugzpodder [ Mon Nov 27, 2006 2:31 pm ] |
Post subject: | |
one more thing to be careful of: getline doesn't actually get the newline, so you must eat up the newline youself! |