We help IT Professionals succeed at work.

problem with getline, strings etc.

amcteer
amcteer asked
on
im trying to get a string using this

string result;
std::getline(std::cin, result, '\n');

what i want it to do is ask for input, and enter a string response, hit enter, then move onto the next question. with what im using up tehre, i enter the response, hit enter, then there is another blank line, well then i hit enter again and it shows my next question, when i fill that out, and hit enter, it skips the second input and my next value is a blank line... what i want it to do is that as soon as i hit enter, i dont want it to go to the next line, i want it to take the string i entered and move onto the next part of my code.

Comment
Watch Question

Author

Commented:
i was using the cin >> result; before this
but the problem is i want whitespace in my strings..

arg

Author

Commented:
string result;
char cresult[100];
cin.getline(cresult,100);
result = cresult;

i resorted to using this, is there a better way?

Author

Commented:
string result;
char cresult[100];
cin.getline(cresult,100);
result = cresult;

i resorted to using this, is there a better way?

Author

Commented:
string result;
char cresult[100];
cin.getline(cresult,100);
result = cresult;

i resorted to using this, is there a better way?
Actually, to my knowledge there isn't a better way.  There was a question posted here very recently that asked the same basic question.  getline() requires a char buffer to receive the input, which would require that the string data type be type-cast to a char[].  According to others who responded to the previous question there is no casting operator that would allow it.  So, in short, no.

Author

Commented:
thats all i wanted to know, thanks
AxterSenior Software Engineer

Commented:
>>getline() requires a char buffer
That's not true of the global getline function.
The global getline function will work with an std::string.

Try the following:
string result;
std::getline(std::cin, result);


That should work.

Author

Commented:
i tried that way initially.. didnt work the way i wanted it to
AxterSenior Software Engineer

Commented:
>>i tried that way initially.. didnt work the way i wanted
>>it to
The code you posted shows you using an additional arguement ('\n').

Did you try it exactly as I have it in my example, (with out the third argument)???

string result;
std::getline(std::cin, result);

Explore More ContentExplore courses, solutions, and other research materials related to this topic.