0
#include <iostream>
using namespace std;

string userInput, userName;

The function below takes an input from the user

string takeInput() 
    {
        cin.ignore();
        getline(cin,userInput);
    }

the takeInput() function would be called and its variable should be stored in the userName variable but nothing shows up when I run the program call the userName in the last cout.

int main() {
    cout<<"Name:    ";
    userName = takeInput();
    
    cout<<"My name is "<<userName;
}
cat lat
  • 37
  • 3
  • 4
    You don't return anything from your function – RoQuOTriX Aug 22 '22 at 12:23
  • Please stop doing `using namespace std` – Spencer Aug 22 '22 at 12:24
  • 1
    you are using global variables and at the same time declare your funciton to return the string, but you dont return it. Frankly this looks like you skipped the section on returning a value from a function in your learning material – 463035818_is_not_an_ai Aug 22 '22 at 12:24
  • 1
    Remove the global variables, instead use local variable `std::string userInput; getline(...); return userInput;` , and then in the main use another local variable: `string userInput = takeInput();`. That should do what you want. Next step is to understand what was changed. – hyde Aug 22 '22 at 12:29
  • 1
    The code should look like this `string takeInput() { string input; cin.ignore(); getline(cin, input); return input; }`. For some reason `return` is something that beginners don't learn, but how else would you return something from a function? As you found out it doesn't happen by magic. – john Aug 22 '22 at 12:32
  • Enable all warnings and use `-Werror`. [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) – Jason Aug 22 '22 at 12:58

0 Answers0