# cin and string question

This topic is 4062 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello all, Once again I am back with a noob question, lol. I did a little project from this book I am reading and am curious about something. If you answer the question with your full name (ie First and Last, with a space in between) it only prints out the first part. Why is that?
//Practice4_1.cpp
#include <iostream>
#include <string>
int main()
{
using namespace std;
string response;
cout << "What is your name? ";
cin >> response;
cout << "It's nice to meet you, " << response;
return 0;
}


Thanks, Shawn *Edit* How would you change to include the full name if someone types it that way? Another question is, how come if I just press enter and type nothing, it doesnt continue?

##### Share on other sites
It only takes the first name because a space is considered an input separator by default. Use cin.getline(string_variable_name,SIZE) to get a sequence of characters of SIZE amount.

Example:
cin.getline(reponse,80);

As for pressing enter causing nothing to happen.. carriage return isn't considered an actual input for cin.

##### Share on other sites
operator>> reads until the first whitespace... encountered after non-whitespace (hence the lack of action when just pressing enter).

An alternative is:

getline( cin, response );

Which will get until the first newline.

Unlike thesilencer's version using istream's member function (e.g. cin.getline(...), this version using the free function (e.g. getline(cin,...)) has the following advantages:

1) It works with std::strings (his requires the use of an ugly C-style character buffer)
2) It requires no explicit size limit after which things will simply be chopped off (the std::string will instead be resized as needed)

Hope this helps!

##### Share on other sites
Thanks to both of you. I think I follow both answers. However, one part of your answer now confused me MaulingMonkey. You said "this version of the free function"...and I notice you said std::string...is this getline (cin,<whatever here>) part of the std namespace? Meaning there is not file to "#include"?

Thanks again,

Shawn

##### Share on other sites
Quote:
 Original post by shawnreThanks to both of you. I think I follow both answers. However, one part of your answer now confused me MaulingMonkey. You said "this version of the free function"...and I notice you said std::string...is this getline (cin,) part of the std namespace? Meaning there is not file to "#include"?

Yes, getline is part of the std:: namespace.
Yes, there's no (new) headers to include to use it (it is part of the <string> header, which you obviously need anyways).

1. 1
Rutin
23
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 29
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631740
• Total Posts
3001966
×