0

My code is doing fine, but when I change cin>>new_person.address into getline, I am having bugs when I run it.

#include <iostream>

using namespace std;

struct person
{
    string name;
    string address;
    int phone_number;
};

person getNewPerson()
{
    person new_person;
    cout<<"Enter a name ";
    cin>>new_person.name;
    cout<<"Enter an address ";
    getline(cin, new_person.address, '\n');
    cout<<"Enter a phone number ";
    cin>>new_person.phone_number;
    return new_person;
}
person printPerson(person a_person)
{
    cout<<"This person name is: "<<a_person.name<<endl;
    cout<<"His address is: "<<a_person.address<<endl;
    cout<<"His phone number is: "<<a_person.phone_number<<endl;
}
int main()
{
    person my_person=getNewPerson();
    printPerson(my_person);
}

When I use getline(cin, new_person.address, '\n'); it skips that statement for no reason and goes to the next one. Dunno what is going on, copy and paste the code please and you will understand.

1 Answers1

0

It is designed like that. In C++ std::cin >> str; reads the next word in stream. More specifically, it reads the next token and tokens are separated by whitespace so effectively they represents one word.

Use getline function to input more than one word.

Mirza
  • 213
  • 2
  • 8