User Input in C++
Read a name and age in C++ with cin. cin >> stops at the first space.
1#include <iostream>2#include <string>3using namespace std;45int main() {6 string name;7 int age;89 cout << "Enter your name: ";10 cin >> name;1112 cout << "Enter your age: ";13 cin >> age;1415 cout << "Hello, " << name << "! You are " << age << " years old." << endl;1617 return 0;18}
Output
Enter your name: Alice Enter your age: 25 Hello, Alice! You are 25 years old.
What's going on
This C++ program reads a name and an age with cin and prints them back. cin >> is the usual first input, and it has a sharp edge.
#include <iostream> and #include <string>
cout / cin from iostream. string name needs <string>.
string name;
int age;
Declared, not filled yet. Until cin writes them, treat them as junk.
cout << "Enter your name: ";
No endl on purpose, so the cursor stays on the same line as the prompt.
cin >> name;
Reads one word. A space stops it. Type Alice Smith and name is just Alice. Then age tries to parse Smith and the stream fails. getline(cin, name) keeps the surname.
cin >> age;
Wants a number. Type twenty and cin fails. Later prints look insane unless you check if (!(cin >> age)).
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
Text and variables in one chain. Sample: Alice and 25 → Hello, Alice! You are 25 years old.
Mixing >> and getline later leaves a newline in the buffer. The next getline then reads an empty line. That's a common bug, not a broken keyboard.
Next useful step is math on those numbers — Sum of Two Numbers.