This chapter will be quite simple: we will see what techniques we use in C ++ to display text on the screen (in a console) and how we get text typed on the keyboard. You will see that it is quite different what we knew in C with printf and scanf.
Configure the IDE for C ++
So far, you have only created C projects in your IDE.
But in C ++ we use another compiler. For example, there is gcc which is a C compiler, and g ++ which is a C ++ compiler. It will be necessary to tell your IDE that you will do C ++, otherwise it will call the wrong compiler (and there it will not work). : – °
Launch your favorite IDE. For my part, you will understand in previous chapters, I work mainly under Code :: Blocks. If you have another IDE like Visual C ++ or Dev C ++ it works too.
Create a new project type console (yes, we return to the console to do our experiments) and think to select C ++.
Creation of a new project. Be sure to select C ++
If you have Dev C ++ the manipulation is the same, I do not remake you from screenshot you are big now.
Under Visual C ++, the project is compiled in C ++ by default, so you will not need to specify anything.
Click “Create” to create the new project.
Code :: Blocks creates a first file named main.cpp in the project with some first lines of C ++ code.
In C ++, your .c files have the .cpp extension. The .h files, they keep, the extension .h.
Some find this illogical and have instead chosen to use .cc (for C ++ sources) and .hh (for C ++ headers). So do not be surprised by this type of notation
Here is the basic code we propose Code :: Blocks in our new project:
1 2 3 4 5 6 7 8 9 | #include <iostream> int main() { std::cout << "Hello world!" << std::endl; return 0; } |
If you have another IDE, delete the code that was generated and use it instead to make sure you work on the same code.
Analysis of the first C ++ source code
Now let’s look at each of these lines of code and see what’s changing for the moment with respect to C.
Include
1 2 3 | #include <iostream> |
2 things :
Shocking first is that there is no extension .h. Indeed, in C ++ standard header files no longer have .h extension, but you will see that there are exceptions (people who have not yet made the evolution). : p
On the other hand, the inclusion directive is no longer the same. Here, it’s called iostream, which means “input-output flow”. Forget stdlib and stdio, these are C headers, we do not use them in C ++ anymore.
We therefore include here the iostream library which contains the necessary tools to display text in the console and recover keyboard input.
Main function ()
1 2 3 4 5 6 7 | int main() { // ... return 0; } |
We find our usual hand function. It works like C: any program starts with the main () function. Nothing shocking here. 😉
The function returns 0, which is again logical since the function must return an int.
FYI, 2 hand forms are possible. This one:
int main ()
… but also this form a little more complicated than you also know:
int main (int argc, char * argv [])
The second form retrieves the call arguments of the program, which is not always done. So you can settle for the first form which is especially easier to remember.
1 2 3 | std::cout << "Hello world!" << std::endl; |
The first line of the hand is the most interesting, it is also the only one that must really surprise you.
Indeed, it does not look like a function call, there are lots of weird signs, no parentheses as we are used to in a function call. Good-bye good evening what is it?
We will discover that now in more detail.
The output stream cout
cout is not a function but a stream, a new element introduced in C ++. Note that it has nothing to do with OOP at the moment.
Rest assured, the functions still exist in C ++ (besides you have seen that there is a hand ()), but you will realize little by little that we use them more in the same way.
The flow cout is the equivalent of the function printf … but in better, in simpler.
Let’s review this famous line of code:
1 2 3 | std::cout << "Hello world!" << std::endl; |
There are two particular keywords in this line: cout and endl. You will notice that they both have the prefix std ::
All keywords in the standard C ++ library use this prefix. Theoretically, one is obliged to put it each time, but it is a little heavy.
Fortunately, we have a solution to simplify life. Add this line of code before the hand ():
1 2 3 | using namespace std; |
So, you can transfer all prefixes std ::
It already makes our code a little easier to read:
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; } |
This is a first point of settled. We will not go into the details of this “using namespace” for the moment (so as not to complicate things unnecessarily).
Let’s take a closer look at this line with cout, now more readable:
1 2 3 | cout << "Hello world!" << endl; |
You see that there is a new symbol: the chevron <
We always meet it in pairs, like this: <<
Imagine that these rafters are actually arrows. As a result, the line is read from right to left:
We take the keyword endl, which means return to the line.
We insert it at the end of the string “Hello world!”
Insert the result obtained in cout.
cout is the contraction of “c-out” (console out = console output). In good French, you must pronounce this “Ci Aoute”.
cout represents the output in C ++ (out = output). The exit of a program, well it’s just the screen. So cout represents the screen.
Race result, this code means that the text “Hello world!” followed by a line break is sent to the screen. One must imagine that the chevrons << indicate the direction in which the data are sent.
This line of code therefore commands a display of text on the screen. Compile and run the program to see:
Hello world!
Let’s get back to endl.
endl is a keyword that means “end of line” (end line in English). In fact, it’s just a word that replaces the \ n you know of C, which was used to make line breaks.
Oh, we can not use \ n in C ++ anymore?
Yes Yes. In fact, the keyword endl was introduced among other things to improve the readability of the source code (not to mix the “n” with the text to display).
You can also test, you will see that the \ n still works:
1 2 3 | cout << "Hello world!\n"; |
The result on the screen is exactly the same:
Hello world!
Cout interest
For the moment, you have to tell yourself that the cout looks like the printf function, with just some more symbols to confuse your mind.
In fact, it’s even easier to use than printf. The interest is seen especially when one wants to display the contents of a variable.
Look at this code, it’s super simple:
1 2 3 4 5 6 7 8 | int main() { int age = 21; cout << "Hi, I'm " << age << "years old" << endl; return 0; } |
Hi, I’m 21 years old
That’s it, it’s intuitive enough that I do not need to explain how it works. 😉
What’s great is that we do not need to bother with the syntax of printf:% d,% lf,% s,% c etc … Here, the language is smarter, it recognizes the type of variable sent to it.
Skeptics? Ok, try adding a string variable in this cout:
1 2 3 4 5 6 7 8 9 | int main() { int age = 21; char pseudo[] = "c4e"; cout << "Hi, I'm " << age << "years old and My name is " << pseudo << endl; return 0; } |
Output:
Hi, I’m 21 years old and My name is c4e.
You see, we sent at once an integer and a string, without specifying the type of variable, and he did not flinch.
As a reminder, in C we should have done:
1 2 3 | printf("Hi, I'm %d years old and my name is %s\n", age, pseudo); |
Not only was it necessary to remember the codes% d and% s, but in addition the variables used are indicated at the end. In C ++ with cost, as you’ve seen, the variable is placed in the middle, making the code easier to read.
Of course, you are not limited to one cost per program.
You can quite make several costs if you want it:
1 2 3 4 | cout << "Hi, I'm " << age << " years old" << endl; cout << "Je m'appelleMy name is " << pseudo << endl; |
The endl at the end of each cost is not mandatory. If you remove it, there will be just no line break.
Train a little with cost, you should get used to it quickly!
The cin input stream
After seeing how to display text, let’s see now how to recover typed text.
Again, it works with a flow system, and you will see that it is a real treat of simplicity.
The key word to know here is cin. It comes in replacement of the practice (but complex) C language scanf function.
cin is the contraction of “c-in”, which means console input. Pronounce it as it should be siouplaît: “Ci in”.
cin represents the entry in C ++. And what is the entrance? It’s the keyboard! Yes, it’s through the keyboard that you enter the data.
cin represents the keyboard and allows to recover text entered by the user.
Here, we’ll do something really original: we’ll ask him his age.
Look how it works
1 2 3 | cin >> age; |
If you are a little observant, 2 things must have shocked you:
The arrows have changed direction! Yes, reading is here from left to right. cin represents the keyboard and sends the data in the age variable. It is therefore necessary to imagine that the data transits from the keyboard to the variable age. This is called a stream.
There is no symbol & in front of age! In C, we should have written & age to send the address of the variable to the function so that it knows where to write in memory. In C ++, it’s more worth it! There is indeed a mechanism that replaces a few pointers called references. We will study this in the next chapter in more detail.
Do not confuse the direction of arrows between cost and cin. The principle is that the data travels in a specific direction: from the memory to the screen (cost) or from the keyboard to the memory (cin).
The arrows are in the direction of movement of the information. With a little common sense, you should not go wrong.
Programs and test de cin
Now let’s test cin in a small program. Here is the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> using namespace std; int main() { int age = 0; cout << "How old are you ?" << endl; cin >> age; cout << "Ah! So you are " << age << " years old!" << endl; return 0; } |
Sorry if I repeat myself, but I find it amazingly simple!
Finish the% d that annoys us, finishes the symbol omissions & in the scanf, finished.
Okay, this new syntax surprises a little when we have done a lot of C before, but it is quickly reassured.
You can also practice asking for the user’s pseudonym:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> using namespace std; int main() { char pseudo[50]; cout << "What is your username ?" << endl; cin >> pseudo; cout << "Hello " << pseudo << endl; return 0; } |
Output:
What is your username ?
c4e
Hello c4e