Lesson 7 - Printing
When programming for VEX, it is useful to output the value of certain variables as your program runs on the robot.
For example, perhaps you want to know the exact value outputted from a sensor. Luckily, C++ allows you to print to the terminal relatively easily by utilizing what is known as the standard input-output stream.
To use this in our program, we would simply write this at the top of our file:
#include <iostream>
This allows us to use a particularly useful command known as std::cout. Using std::cout, we can print values and keep track of aspects of our program that would otherwise function “invisibly” to us.
Here’s an example:
int i = 0;
std::cout << i << std::endl;
So what’s going on here? Well, we have a few things:
“i” is defined as an integer variable with a value of 0
std::cout is called and the value of i (0) is printed to the terminal
Let’s break down what we see in this print statement. First, std::cout is called to let the program know that we are printing to the terminal. Then, we use the insertion operator << to “put” i into our print statement, then we put std::endl in at the end. std::endl is simply an end line statement. We are telling the program to add a newline character (go to the next line down).
What’s the difference without std::endl? Well, let’s first see an example with it:
int i = 0;
std::cout << i << std::endl;
std::cout << i << std::endl;
std::cout << i << std::endl;
std::cout << “value of integer i is: ” << i << std::endl;
This would output:
0
0
0
value of integer i is: 0
Whereas with this program:
int i = 0;
std::cout << i;
std::cout << i;
std::cout << i << std::endl;
std::cout << “value of integer i is: ” << i << endl;
This would output:
000
value of integer i is: 0
You can imagine how this might get more cluttered and harder to read once we have more/larger numbers or are tracking the value of a double type variable.