0

I'm probably an idiot, I know. This is probably a duplicate, but for the life of me I couldn't find an answer after looking for over an hour. I guess I don't know how to phrase a search. All I want is to be able to print out a string from a function based on user input. This isn't part of the program I'm building right now, but it illustrates my problem.

#include "../std_lib_facilities.h"

string make_name()
{
    string name;
    int selection;
    cout << "Enter 1 steve. Enter 2 Mike.\n\n";
    cin >> selection;

    if (selection == '1')
        name = "Steve";
    else if (selection == '2')
        name = "Mike";

    return name;
}

int main()
{
    cout << "Make a name\n";
    make_name();
    cout << "Your name is " << make_name;
    keep_window_open();
}

Instead of printing Mike or Steve, it prints nonsense. I've been working on all the other parts of my program, but now this is the only problem I have. So, lay into me. What am I doing wrong?

Nickless
  • 15
  • 3
  • Show the contents of `std_lib_facilities.h` – M.M Nov 25 '14 at 05:42
  • Where do you think the return value of `make_name()` goes to? – Yu Hao Nov 25 '14 at 05:43
  • If it defines that `string` is `std::string` then this code would show a blank name. If you see garbage it suggests that something else is going on , e.g. `typedef char *string;` or some other ghastfulry – M.M Nov 25 '14 at 05:43
  • **C++ Books:** http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Galik Nov 25 '14 at 06:55

2 Answers2

0

This is because of

if (selection == '1')

Here you are comparing an int with char. That means value of '1' would be the ASCII value of this character which is not 1.

Correct conditional statement should be:-

if (selection == 1)
ravi
  • 10,994
  • 1
  • 18
  • 36
0

The reason you're getting garbage printed is because at this line in main:

cout << "Your name is " << make_name;

You're printing out the address of the function 'make_name', as opposed to the result of calling it.

The fix is to capture the result of calling the function and print that out instead:

int main()
{
    cout << "Make a name\n";
    string name = make_name();
    cout << "Your name is " << name;
    keep_window_open();
}

One other latent issue is inside of your 'make_name' function, your two conditions:

if (selection == '1')
    name = "Steve";
else if (selection == '2')
    name = "Mike";

You're comparing 'selection', which is an int, to the ASCII characters 1 and 2, which is not what you want.

Change that to:

if (selection == 1)
    name = "Steve";
else if (selection == 2)
    name = "Mike";

and you should have the desired result.

Note: Also, consider initialising your 'selection' variable to 0. That should prevent unexpected results if someone were to input "hello", instead of a number.

Jared Mulconry
  • 479
  • 3
  • 8