Class Member Function

Jun 19, 2013 at 6:09am
I dont understand why calling cin before calling my member function screws up the output, see below:


My Class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  struct Person{
    std::string name;
    std::string address;
    Person& newUser();
    Person& data() {
    std::cout << "Name: " << name << std::endl << "Current Address: " << address
    << std::endl;
    return *this;
    }
};

 Person& Person::newUser() {

        std::cout << std::endl << "Please enter your full name: " << std::endl;
        std::string::getline(std::cin,name);
        std::cout << "Please enter your full address: " << std::endl;
        std::string::getline(std::cin,address);
        return *this;
}


This doesnt work:

1
2
3
4
5
6
7
8
9
int main()
{
    Person tempUser;
    char go;
    cout << "Would you like to add a user? (y/n) ";
    cin >> go;
    if(go == 'y')
    tempUser.newUser();
    cout << tempUser.name << " " << tempUser.address;}


This works, after commenting out my call to cin, function works properly.:

1
2
3
4
5
6
7
8
9
int main()
{
    Person tempUser;
    char go = 'y';
    cout << "Would you like to add a user? (y/n) ";
    //cin >> go;
    if(go == 'y')
    tempUser.newUser();
    cout << tempUser.name << " " << tempUser.address;}
Last edited on Jun 19, 2013 at 6:10am
Jun 19, 2013 at 6:15am
after you use cin, below it, you do cin.ignore()
Jun 19, 2013 at 6:33am
Thank you, it was driving me mad, c++ primer has not taught that and im in chaper 7, in fact the book doesnt refer to it once... Anyway for reference should someone find this needing an answer for why:

 
cin leaves the newline character in the stream. Adding cin.ignore() to the next line clears/ignores the newline from the stream.
Last edited on Jun 19, 2013 at 6:35am
Topic archived. No new replies allowed.