cin and string question

Started by
3 comments, last by MaulingMonkey 16 years, 10 months ago
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?
Advertisement
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.
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!
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
Quote:Original post by shawnre
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"?


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).

This topic is closed to new replies.

Advertisement