A question about getline and cin

This is a discussion on A question about getline and cin within the C++ Programming forums, part of the General Programming Boards category; here is my code and if you run it you 'll see that it has a bug Code: #include <iostream> ...

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    17

    A question about getline and cin

    here is my code and if you run it you 'll see that it has a bug


    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    class example
    {
        public:
            example();
            void print(){cout<<itsName<<endl<<itsNumber<<endl<<endl;}
        private:
            string itsName;
            int itsNumber;
    
    };
    
    example::example()
    {
        cout<<"Enter Name"<<endl;
        getline(cin,itsName);
        cout<<"Enter Number"<<endl;
        cin>>itsNumber;
    }
    int main()
    {
        example a[3];
        for(int i=0;i<3;i++)
        {
            a[i].print();
        }
        return 0;
    }
    BUT if i change getline(cin,itsName) with cin>>itsName it works fine
    can you tell me why?

    ps i'm a novice (c++) programer so there is a high possibility that my question is silly

  2. #2
    Just kidding.... fnoyan's Avatar
    Join Date
    Jun 2003
    Location
    Still in the egg
    Posts
    269
    refer the expected parameter types for getline()
    istream::getline - C++ Reference

    and implementation of std::cin
    cin - C++ Reference

  3. #3
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    107
    It will only work right if you enter one name otherwise if you enter maybe you name plus your surname the cout the 'itsname' it will give you the name you entered first only.

  4. #4
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,649

  5. #5
    Registered User
    Join Date
    Apr 2012
    Posts
    17
    Quote Originally Posted by rags_to_riches View Post
    thanks
    it solved my problem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question About Getline
    By bengreenwood in forum C++ Programming
    Replies: 2
    Last Post: 04-28-2009, 05:13 PM
  2. getline question
    By dhrodrigues in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2004, 09:07 AM
  3. Question about cin.getline
    By newy100 in forum C++ Programming
    Replies: 6
    Last Post: 11-24-2003, 06:13 PM
  4. A question about getline
    By jriano in forum C++ Programming
    Replies: 2
    Last Post: 06-24-2003, 02:21 AM
  5. getline question
    By Swaine777 in forum C++ Programming
    Replies: 2
    Last Post: 03-30-2003, 05:17 AM

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