Thread: using cin and strings

  1. #1
    Registered User
    Join Date
    Apr 2005

    using cin and strings

    I am writing a program where the user needs to input a string. The problem is that the first word in the string always gets cut off and a space stays. Here is my code:

    //a class has been created and a new variable called var is also present
    //name is of type string
    while(selection != 0){
    	//some menu display
    	cout<<"Please choose an action: ";
    	    case 1:
                   cout<<"Name: ";
    		getline(cin, name);
    	    //some other cases down here
    for example, if I enter name John Doe, then the String name contains " Doe" instead of the whole name. How can I fix my code to fix this?


  2. #2
    Let's do some coding! Welshy's Avatar
    Join Date
    Mar 2005
    Staffordshire University, UK
    Get rid of the 'cin >> name' line.

    That line assigns the string 'John' to name, but then when you use getline it writes over the top of it with ' Doe', therefore the string name then contains ' Doe'.

    At least that's what it looks like to me :P

  3. #3
    Registered User
    Join Date
    Apr 2005

    thanks for the quick reply

  4. #4
    Registered User
    Join Date
    Jan 2005
    After you make that fix, be careful when mixing operator >> and getline. The newline in the stream from the 'cin >> selection' will cause the getline call to put nothing into the name field. You have to ignore() the newline character after the cin >> call.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting strings with Cin
    By warfang in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2007, 03:25 PM
  2. CIN Input count question?
    By kamran in forum C++ Programming
    Replies: 5
    Last Post: 10-24-2006, 04:06 PM
  3. Strings allowing spaces?
    By Dan17 in forum C++ Programming
    Replies: 13
    Last Post: 02-04-2006, 03:15 PM
  4. cin for strings?
    By samGwilliam in forum C++ Programming
    Replies: 4
    Last Post: 04-03-2005, 01:35 PM
  5. cin strings till eof
    By bfedorov11 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2003, 07:27 AM