Thread: String problem after space

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    10

    String problem after space

    Hello,

    In some functions of my program this code doesn`t work normally

    Code:
            string w1;
            string w2;
    
            cout<<"1st msg: Enter 2 words: ";
            getline(cin,w1);
            cout<<endl;
    
            cout<<"2nd msg: Enter 2 words: ";
            getline(cin,w2);
            cout<<endl;
    
            cout<<endl<<"w1: "<<w1<<endl;
            cout<<"w2: "<<w2<<endl<<endl;
    But when i run it is some functions(except main and some others) of my program shows other output.
    Code:
    1st msg: Enter 2 words:
    2nd msg: Enter 2 words: word1 word2
    
    
    w1:
    w2: word1 word2
    My variables are again local, any ideas whats the problem ?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Most likely there is an unprocessed newline in the input stream, left over from some previous

    Code:
    cin >> someVariable;
    You'll need to clear the stream of any unread characters before calling getline, e.g

    Code:
    #include <limits>
    ...
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.ignore(
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism and generic lists
    By Shibby3 in forum C# Programming
    Replies: 9
    Last Post: 07-26-2010, 05:27 AM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. someone who is good at finding and fixing bugs?
    By elfjuice in forum C++ Programming
    Replies: 8
    Last Post: 06-07-2002, 03:59 PM