Joel Verhagen

a computer programming blog

Taking String Input in C++ Command Line

If you're learning C++, you've probably heard all about the basic input/output tools call cin and cout. Well, say you want to get string input from a user of your new command line program. I was having a pretty depressing day a while back and I wanted to make a program that gets to know me then complements me. Well, it's going to have to ask my name right? Well this is just too easy, right?

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

int main()
{
    cout << "Computer: What's your full name?" << endl;

    cout << "You: ";
    string name;
    cin >> name;

    cout << "Computer: Hi, " << name << "! You're a real swell person!";

    return 0;
}

And here was the output I got:

F:\Programming\ForBadDays\bin\Release>ForBadDays.exe
Computer: What's your full name?
You: Joel Verhagen
Computer: Hi, Joel! You're a real swell person!
F:\Programming\ForBadDays\bin\Release>

What the heck! Computer already forgot my last name! How do you think that makes me feel..

Well, what's really going on there is cin only reads in to the first space in the input. So if you type in "Emma Charlotte Duerre Watson", it would only store "Emma" in the name variable. This is how you get the whole line:

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

int main()
{
    cout << "Computer: What's your full name?" << endl;

    cout << "You: ";
    string name;
    getline(cin, name);

    cout << "Computer: Hi, " << name << "! You're a real swell person!";

    return 0;
}

Notice how I used the getline function. Now the whole input up to the first return or newline character is stored in the name variable. And here is the example output:

F:\Programming\ForBadDays\bin\Release>ForBadDays.exe
Computer: What's your full name?
You: Joel Verhagen
Computer: Hi, Joel Verhagen! You're a real swell person!
F:\Programming\ForBadDays\bin\Release>