using cin and strings

This is a discussion on using cin and strings within the C++ Programming forums, part of the General Programming Boards category; I am writing a program where the user needs to input a string. The problem is that the first word ...

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    4

    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:


    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: ";
    	cin>>selection;
    	
    	switch(selection){
    	    case 1:
                   cout<<"Name: ";
    		cin>>name;
    		getline(cin, name);
    		var.addname(name);
    		break;
    	    //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?

    thanks

  2. #2
    Let's do some coding! Welshy's Avatar
    Join Date
    Mar 2005
    Location
    Staffordshire University, UK
    Posts
    168
    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
    Posts
    4
    oops

    thanks for the quick reply

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    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, 04:25 PM
  2. CIN Input count question?
    By kamran in forum C++ Programming
    Replies: 5
    Last Post: 10-24-2006, 05: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, 02:35 PM
  5. cin strings till eof
    By bfedorov11 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2003, 08:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21