I would like some help with this. I know is a very noob and rookie question.
I'm trying to get a value from a function, however, the scope is not the same, and destroy is being called before that I can use it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
constchar * getUserInput ()
{
std::string userInputStr = "40";
return userInputStr.c_str ();
} // userInputStr destroy is being called, so the value is lost
int main ()
{
constchar *userInput = getUserInput ();
//expected output The Number is 40
//current output The Number is (null)
printf ("The Number is %s\n", userInput);
return 0;
}
One workaround that I found is making userInputStr local in the class which is awful given that I don't need that var living in the class. is there a proper way to achieve this?
The first thing is that if you are going to use C++ then you should code in C++. printf is not the norm in C++. Nor are C-style strings. So the C++ answer is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
std::string getUserInput()
{
std::string str;
std::cout << "Whassup? ";
std::getline(std::cin, str);
return str;
}
int main ()
{
std::string userInput = getUserInput();
std::cout << "The user entered: " << userInput << '\n';
return 0;
}
Hello, thanks for helping me!!!!, it works. I mean by using string instead const char *, here is the new code... https://onlinegdb.com/ryFlvJU-m
So, but I'd like to learn how to handle the pointer in C example. I believe the problem in C was the pointer, and I could run into similar issues in the future with C++.
If I understand well the function is returning the pointer of userInputStr, that was destroyed at the end of the function causing the value is not persisting later.
Is there a way to solve the issue pointer in C? I mean besides of set userInputStr as global var in the class.
I do appreciate if you can explain that part. Otherwise, cool your help was very nice, thanks! :)
If you have your heart set on returning a char* from the function, then the C-style string should be allocated "on the heap" (i.e., dynamically through the "new" operator) instead of on the stack. Something like this:
But in C++ it's best to avoid new as much as possible by using std::string, std::vector, std::list, etc., since dynamic allocation can lead to nasty errors.
for a simple, single threaded, easy to use solution you can do this:
1 2 3 4 5 6 7 8 9
char * foo()
{
staticchar c[1000]; //biggest value you expect to get for a string in the program goes here.
//assign c here, or it can be a constant above with "value" approach
// whatever
return c; //this is valid because the static keyword keeps c around until the program ends.
//this approach will cause you no end of grief if you multi-thread it.
}
This stuff is old school C and early C++ code. It is not wise to use it anymore, unless you are trying to tie a C and C++ program together, or editing legacy code, or something like that. Listen to people about string etc.