About String input through cin.

+1 Nayab Basha Sayed · May 13, 2015
#include <iostream>
#include <string>
using namespace std;

class yoDing{
    string str;

int main()
    yoDing yo;

When I gave input as -- Nayab Basha Sayed, It only took first word 'Nayab' but not entire string. Why is that? and How to input entire 3 three letters through cin?

Post a Reply


Oldest  Newest  Rating
+2 Michael Bradford · May 20, 2015
Also be wary there is a very common pitfall when mixing the use of cin >> variable and getline(). Getline looks for the '/n' character as a delimiter and when you use cin you type a value and hit the enter key (the enter key puts '/n' in the buffer stream) 

but cin only takes what you typed prior to pressing enter and leaves the '/n' character in the buffer stream... if you just keep using cin, cin will handle the whitespace character accordingly but if you use a getline AFTER using a cin. Getline will look into the input buffer, see the '/n' character sitting there and say "Cool I'm at the end of the line now" 

and it wont actually have gotten anything or prompted you for anything because it thinks it already got the line. The solution to this problem is to use the cin.ignore() command after using cin or before using getline() to get rid of the '/n' character so getline looks for your input properly.

Just something you will inevitably run into thought I'd let you know.
+2 K D · May 14, 2015
because cin veiws any form of white space ( a space, tab, new line) as end of input.

if using char arrays use:
cin.getline(yo.str, lengthOfArray );

if the c++ string objects use either:
getline(cin,yo.str);        // '\n' is the delimiter for this one by default

getline(cin, yo.str,'\n');  // the last parameter '\n' is a way of giving a different delimiter for it to look for but it can cause some issues  with input if you change the delimiter
+1 Troy Jones · May 13, 2015
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator