Data Types
The data type decides what values a variable can hold. So far, you've used int. To start with, these five types are all you need:
#include <iostream>
#include <string>
int main() {
int students = 28;
double price = 12.5;
char group = 'B';
bool isWeekend = true;
std::string city = "London";
std::cout << students << "\n";
std::cout << price << "\n";
std::cout << group << "\n";
std::cout << isWeekend << "\n";
std::cout << city << "\n";
}This prints:
28
12.5
B
1
Londonintis a whole number, positive or negative:28,-5,0.doubleis a decimal number, written with a decimal point:12.5,-0.25.std::coutprints it without extra zeros:2.50as2.5and3.0as3.charis one character in single quotes:'B','7','?'.boolis a truth value (a Boolean): eithertrueorfalse. It's useful for questions whose answer is yes or no: is it the weekend? does the player have the key?std::coutprintstrueas1andfalseas0, which is why you see1in the output above.std::stringis text (a string, as in a string of characters) in double quotes:"London". It comes from the standard library, so it's written withstd::, just likestd::cout. It needs#include <string>at the top of the program, just asstd::coutneeds#include <iostream>.
You choose the type by what the variable will hold: the number of students is always a whole number, a price can have cents, and a name is text.
Typical mistakes:
- One character in double quotes:
char group = "B";ends with the errorcannot initialize a variable of type 'char' with an lvalue of type 'const char[2]'. The compiler is saying that the text"B"can't be stored in achar. One character goes in single quotes:'B'. - A decimal comma: in many countries, people write 12,5. In C++,
double price = 12,5;ends with the errorexpected unqualified-id, because the comma means something else in C++. Write decimal numbers with a point. - A decimal number in an
int:int price = 12.5;compiles, but only12is stored. The decimal part is thrown away. - If you forget
std::,string city = "London";ends with the errorunknown type name 'string'; did you mean 'std::string'?
Instructions
- 1
The program doesn't compile yet, because it prints variables that don't exist. Below the comment, create them, each with the right data type:
namewith the value"Emma"agewith the value16heightwith the value1.68groupwith the value'B'isStudentwith the valuetrue
- 2
Run the program. It should print:
Name: Emma Age: 16 Height: 1.68 m Group: B Is student: 1 - 3
Below the prints, create a variable
isAdultof typeboolwith the valuefalse, and print it like this:Is adult: 0