12/19/2016
Here we will go over more usages of variables.
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main() {
int x;
x = 3;
// Visual Studio only for the following line.
getchar();
return 0;
}
In this main function, we declare a
variable x of type int,
and then give it the value
of 3. These are two
different statements, as denoted by the semicolon
(;).
We can simplify these two lines down
to int x = 3;. This will
declare and construct it with the value
of 3.
Writing cout << x;
would then print out 3 to the terminal.
The types of variables matters as much as their values. By
simply replacing the
word int
with string will change
the meaning of our program. A string and an integer are
distinct types obviously.
Try making a string variable and name
it message. Construct it
with a message you wish to show the user. Then reassign
the message to something else.
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main() {
int x = 3;
cout << x;
string message = "My first message!";
message = "My second message!";
cout << message;
// Visual Studio only for the following line.
getchar();
return 0;
}
Our new program will print out "3My second message!". To
insert a line break
between x and
the message, we have to
print out "\n".
Put the following line before we print out the message to do this:
cout << "\n";