Thread: Having problem in cin with strings.. :( Help!!

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    82

    Having problem in cin with strings.. :( Help!!

    Input: fred
    output: Name 1: fred
    Name 2:
    input: fred silv
    output: Name 1: fred
    Name 2: silv
    Help me plz..!! Why this problem is occuring??


    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string name;
        string name2;
    
        cout << "Enter Name " ;
       //getline (cin, name);
        cin >> name;
        cin.ignore();
        getline (cin, name2);
        cout << "name 1 :" << name << "\n name 2: " << name2 ;
    
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    cin >> name;

    getline (cin, name2);

    So be consistent, and use getline() for both inputs.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    82
    i knw that.. but why my this program is not working when every thing is correct?? :\

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > but why my this program is not working when every thing is correct?
    If your program isn't working, then how can you say it is correct?

    cin >> var stops at white-space
    cin.getline() stops at newline

    So if you type in "hello world", you'll end up with "hello" in the first case (and "world" ends up in another variable), or you have "hello world" in the second case.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Strings, Please help!
    By varus in forum C++ Programming
    Replies: 8
    Last Post: 11-27-2006, 11:47 PM
  2. Problem with strings
    By PPhilly in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2006, 06:56 PM
  3. Problem with Strings
    By osal in forum C Programming
    Replies: 2
    Last Post: 07-20-2004, 03:02 PM
  4. problem with my strings
    By wiresite in forum C++ Programming
    Replies: 11
    Last Post: 05-03-2004, 02:13 PM
  5. please help me with Strings problem
    By suezq in forum C Programming
    Replies: 13
    Last Post: 04-03-2003, 08:38 PM