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?
And here was the output I got:
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:
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: