0

I'm trying to get user input for a string pointer in my code within a constructor. My actual pointer was created in my class.

When I try it this way, nothing gets stored.

UserInfo::UserInfo() 
{
    cout << "Please enter your PhoneNumber: ";
    cin >> phoneNum;

    cout << "Please enter your name: ";
    name = new string();

    getline(cin, *name);
    assert(name != NULL);
    cin.ignore(80, '\n');
}

I've also tried to do it this way:

name = new string(getline(cin,*name));

But, that doesn't work either.

trincot
  • 317,000
  • 35
  • 244
  • 286
Jacob
  • 1
  • 1
  • 1
    You are mixing cin and getline(). That creates issues that are frequently asked about here. [See this for example](https://stackoverflow.com/a/18786719/631266) Aside: Why use a string pointer rather than a string? It seems like using a string would be more appropriate. Also easier to get right re copying, assignment and destruction and require writing less code. – Avi Berger Nov 17 '22 at 01:53
  • 1
    Does this answer your question? [Using getline() in C++](https://stackoverflow.com/questions/18786575/using-getline-in-c) – Avi Berger Nov 17 '22 at 01:56
  • If you pressed [enter] after typing the phone number, `cin >> phoneNum;` will read the number and the very next thing `getline` will read is a newline. You'll get an empty string. – Drew Dormann Nov 17 '22 at 01:58
  • 7
    Side note: you almost never want a pointer to `std::string`. A large part of `string`'s job is to hide the ugliness of dynamic memory management from you, but if you `new` a `string`, you're taking that responsibility back onto yourself. And when you consider that at its most basic a `string` is a pointer to a `char` array and an integer storing the length, throwing another pointer into the mix doesn't gain or save you very much. It's almost all cost. – user4581301 Nov 17 '22 at 02:05

1 Answers1

0

Be more careful when you work with cin and getline in the same code block. The >> operator leaves a new line character in the input buffer, and the getline is usually ignored.

Therefore, there are two reliable options. Use std::cin.ignore() or getline() as follows:

std::cout << "Please enter your PhoneNumber: ";
// Don't forget to use the dereference operator to let data be stored in it.
std::cin >> *phoneNum;
std::cin.ignore();

// --- OR ---

std::getline(cin, *phoneNum);

Note that it is not recommended to make a std::string pointer. It is built to hide the complexity of dynamic memory management and store strings in an easy way.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34