Help with My Pointer Problem in Function - Input Skipping

  • Thread starter Thread starter DivGradCurl
  • Start date Start date
  • Tags Tags
    Pointers
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 3K views
DivGradCurl
Messages
364
Reaction score
0
In my program have a function like this:

Code:
void * changeInfo(bool *flag, string *NewName)
{
     if (!(*flag))
     {
     cout << endl << "Enter the new Name: ";
     getline(cin, *NewName);
     cout << *NewName;
    }
}

My problem is reading the input using the pointer to a string. The program simply skips that part. It is weird that "getline" works if I'm using the commands within the main. Yes, I prototype and call the function in addition to passing the inputs. It does not seem to be trivial. I've spent a lot of time trying to fix this, but no success so far.

Any help is highly appreciated.
 
Physics news on Phys.org
How are you calling the function, in main() or wherever? If a function expects to receive pointers, and main() has the actual objects, you need to specify when you call the function that you're passing the addresses of the objects rather than the objects themselves:

Code:
bool f;
string s;
changeInfo (&f, &s);

Also, your function doesn't change the value of 'flag', so there's no need to pass it by pointer. Bools are small enough that they can be passed by value efficiently.

(Personally, in C++ I prefer to pass parameters that need to be modified in the function, by reference instead of by pointer, but this is basically a matter of personal preference only, so I won't press this issue.)

Finally, why did you declare the function as 'void *'? If the function doesn't return anything via a 'return' statement, it should be declared simply as 'void'.
 
Unfortunately, I can only use pointers since this is one of the requirements of my project. I'm using * after void because I thought it was the right procedure if the inputs are pointers. I have a lot to learn. :)

I'm going to remove the flag and inspect my main function. I'll get back to you if I have more questions.

Thank you
 
What I meant about the flag is that you can pass it this way:

In main():

Code:
bool f;
string s;
// I assume that you set the value of f somewhere in between here...
changeInfo (f, &s);

In the function:

Code:
void changeInfo(bool flag, string *NewName)
{
     if (! flag)
     {
     cout << endl << "Enter the new Name: ";
     getline(cin, *NewName);
     cout << *NewName;
    }
}

Passing the flag by value is more efficient than passing by pointer, because the function doesn't have to dereference a pointer first, before using the value of the flag. It just uses the value directly.