Here are some instructions on how to make a program in the C++ programming language that would ask the user for their name, then say hello to them.
Prerequisites
- A text or code editor and compiler or an Integrated Development Environment(IDE for short) with C++ compiling installed
- Knowledge from the Hello World tutorial
| Be careful when downloading programs from the internet; make sure to ask your parent or guardian first and download compressed files. If you just want to see how this works then use an online IDE. |
Scratch Code
If you were making this with Scratch, you would code it like this:
when gf clicked ask [What is your name?] and wait set [name v] to (answer) ask [What is your favourite number?] and wait set [number v] to (answer) say (join [Hello, ] (join (name) (join [, I like ] (join(number) [ too!]))
C++ Code
The C++ code for is somewhat similar to the Scratch code shown above. It is shown below:
#include <iostream>
#include <string>
using namespace std;
int main() {
String name;
int number;
cout << "What is your name?" << endl;
cin >> name;
cout << "What is your favourite number?" << endl;
cin >> number;
cout << "Hello, " << name << ", I like " << number << " too!" << endl;
}
Explanation
The following lines are new to this program:
#include <string>imports thestringlibrary, so the program can store words.String namemakes a new variable that holds a string called 'name'.int numbermake a new variable that holds an integer called 'number'.cin >> nameandcin >> numbertake what has been typed in by the user, and sends it to the specified variable.
Variables
Variables store data. They can be interacted with by either sending data to them with the >> operator, or setting them with an equal sign, like so: variable = data.
cin
cin is used to get input from the user. Anything that the user types into the terminal will go into cin.