0

I am trying to make a program to ask for their name, and then say "Hello, (their name)!" back. Here's my code so far, the "getchar()" is just so it pauses and I can see the output.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string name;
    cout<<"What is your name?:";
    cin>>name;
    cout<<"Hello, "<<name<<"!";
    getchar();
    return 0;
}

This asks me for input, and I input my name, and then the application closes! I don't know why and how to fix it! Please help!

EDIT: Found out how to solve it. Finished code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string name;
    cout<<"What is your name?: ";
    cin>>name;
    cout<<"Hello, "<<name<<"!\n";
    system("PAUSE");
    return 0;
}
  • The new line is still in the stream when `getchar` is invoked, so the character `'\n'` is extracted and the screen closes. – David G Jan 02 '14 at 22:32
  • 4
    Try using `std::cin.ignore(std::numeric_limits::max(), '\n');` before the the `getchar()`: almost certainly the `'\n'` from entering the `name` is still in the buffer. – Dietmar Kühl Jan 02 '14 at 22:33
  • possible duplicate of [Visual studio 2010 exiting after program ends](http://stackoverflow.com/questions/2639891/visual-studio-2010-exiting-after-program-ends) – pippin1289 Jan 02 '14 at 22:33
  • possible duplicate of [getchar() doesn't work well?](http://stackoverflow.com/questions/8442644/getchar-doesnt-work-well) – Geoff Reedy Jan 02 '14 at 22:35

2 Answers2

5

Dietmar wrote the correct answer, unfortunately as a comment for some strange reason.

getchar() is already a hack but I'll let you off. Replacing it with something like system("PAUSE") is even more of a hack, so let's not go there.

Your getchar() is working, but there is still a \n in the buffer from just after the name (remember, you had to type ENTER to submit it!) and this is satisfying getchar() without further user intervention.

You can get rid of that ghost newline:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getchar();

However, please consider configuring your execution environment to keep the console window, rather than making your program take on responsibility for this. It's there to take user input and give computed output, not to manage terminal windows.

If you're on Windows, I find cmd.exe /K myProgram to be helpful — the /K runs your program then keeps the command prompt open.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
-1

just use the function getch() from <conio.h> !

#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

    int main()
    {
        string name;
        cout<<"What is your name?:\n";
        cin>>name;
        cout<<"Hello, "<<name<<"!\n";
        getch();
        return 0;
    }

Very easy to use, safe and way better than system ("pause")!

Hans Peter
  • 571
  • 1
  • 8
  • 14