Declaring Variables in C++

Declaring Variables in C++

Say you want to store data for temporary use in a program. You will have to declare variables to input the data. Luckily, declaring variables in C++ is very easy. This simple program gets the user’s age as input and displays it back to the screen. Here is the source code:

#include using namespace std;int main(){   int age;   cout : ";   cin >> age;   cout 

To declare the variable "age," simply type the data type (int) in front of it. Notice that you can specify the type of data you want the function main to return.This next program uses a few more variables. It retrieves the user's age, as well as their height, weight, hair color, and eye color.

#include #include using namespace std;int main(){   int age, feet, inches, pounds;   string hair, eye;   cout ." > age;   cout > feet >> inches;   cout > pounds;   cout > hair;   cout > eye;   cout 

Notice that it's possible to declare different variables of the same type in one line. Simply separate them by a comma. The previous code also includes a file called string and uses strings to store characters.

A note about data-handling and error detection: when you have an integer as a variable, there is nothing you can do to prevent a user from trying to enter invalid data.


Share the Post: