Let's take a more practical look at implementing user input and output in C++. Consider an example where we want to ask the user for their name and age, and then thank them for providing the information. This scenario is quite analogous to a user interacting with a web interface, where they might fill out a form with their information.
We use cout
to ask for the user's name: cout << "Please enter your name: ";
. The software then waits for the user's input, which is stored in the userName
variable. We repeat this process to get the user's age.
Now, we have stored the user's name and age in our variables, just like how we'd store form data in JavaScript or Python. In our last statement, we string together multiple cout
operators to print a sentence with the variable values embedded in it, echoing to the user their name and age.
Make sure to swap in your name and age when you test this code.
xxxxxxxxxx
using namespace std;
int main() {
string userName;
int userAge;
cout << "Please enter your name: ";
cin >> userName;
cout << "Hello " << userName << "! Now, please enter your age: ";
cin >> userAge;
cout << "Thanks for the information, " << userName << ". You are " << userAge << " years old.\n";
return 0;
}