Python to C++, A Data Scientist’s Journey to Learning a New Language –Output, Data Types, Variables, and User Input

Daniel Benson
Analytics Vidhya
Published in
13 min readApr 10, 2021

Introduction

Welcome back, reader, to the next installment of my Python to C++ series! Last week I gave a brief introduction to the series and went over some of the basic similarities and differences between the Python and C++ languages. I ended things by creating a Hello World program in each language and explaining the differences in the code line by line.

In this week’s installment I will be going over differences and similarities in general output, data types, variables, and collecting input form the user between the two languages. Let our journey continue!

Printing and Output

Printing output to the user is one of the most vital aspects to learn in programming. Whether the user is being given instructions, being told a story, or being commended for their spectacular performance some form of output is needed in most every program, regardless of what language the programmer is using.

In Python this method is built in to the basic Python library and need only be called for it to run successfully. We saw this last week in our Hello World program. Running the following code is all that is needed to receive output:

print(“This is a test…”)print(“Printing is simple in Python…”)

Typing the following into the terminal:

$ python3 output.py

returns the following output:

>> This is a test...
>> Printing is simple in Python...

We call the print method by typing in print() making sure to include the open and closed parentheses. Within these parentheses we pass in a parameter, in this case what we want to see printed out to the terminal — because we are printing out a phrase, or string, we must ensure to enclose the phrase quotation marks. We will learn more about strings later on.

This is slightly more complicated within the C++ language, as the print or output method isn’t built in to the base c++ library but a separate library altogether, called the iostream library, short for input output stream. As we saw last week we are first required to call the library using #include. Then, when calling specific methods within the iostream library we must make a call to the library, in this case that call is made by typing in std. This is followed up by making a call to the method we want to use. Since we are printing output we will use the cout method. This is followed by two left arrow symbols, “<<“ indicating to the compiler that what comes next is what we want to print out. Again we are working with phrases, or strings, so we must ensure they are surrounded by quotation marks. Finally, as usual in C++, we must end every statement with a semi-colon — here I wish to point out that with newcomers, whether from a different language or new to coding altogether, one of the most common mistakes is leaving out the semi-colon after a statement. Always check! The following code is used to print output in C++:

#include <iostream>int main(){std::cout << “This is a test…”;std::cout << “Printing in C++ is a bit more complicated…”;std::cout << “\nThis is a test…\n”;std::cout << “Printing in C++ is a bit more complicated…\n”;return 0;}

Typing the following in to the terminal:

$ g++ -o output output.cpp
$ ./output

Returns the following output:

>> This is a test...Printing in C++ is a bit more complicated...
>> This is a test...
>> Printing in C++ is a bit more complicated...

You will see that I used two separate approaches in this code. One with a “\n” at the end of the output phrase and one without the “\n” at the end of the output phrase. You will find that when printing the two phrases without the “\n” both phrases end up printing to the same line, whereas the phrases that end in “\n” each print one separate lines. You might recognize this from the Python language, and its use here is exactly the same. The “\n” tells the compiler that we want to create a new line after whatever came before the newline symbol. There is another way to do this in C++ which we will look at a bit later.

Data Types

Everything the programmer uses for input, output, calculations, etc. has a specific data type. This is true in most every programming language. Data types are used to help the computer understand what exactly it is working with. Many of the data types are fairly similar across different programming languages, and for the most part that is the case between Python and C++. The following is the full body of code we will be using in both languages. We will break down the data types section by section, first in python:

# This is an inline comment in python# strprint(“Hello World!”)print(type(“Hello World!”))# intprint(1)print(type(1))# floatprint(1.5)print(type(1.5))# boolprint(True)print(type(True))

then in C++:

//This is an inline comment in C++#include <iostream>#include <typeinfo>#include <string>int main(){// stringstd::string a = “Hello World!”;std::cout << a << std::endl;std::cout << typeid(a).name() << std::endl;// intstd::cout << 4 << std::endl;std::cout << typeid(4).name() << std::endl;// floatfloat c = 4.5;std::cout << c << std::endl;std::cout << typeid(c).name() << std::endl;// doubledouble d = 4.555555555555555555;std::cout << d << std::endl;std::cout << typeid(d).name() << std::endl;// boolstd::cout << true << std::endl;std::cout << typeid(true).name() << std::endl;// charstd::cout << ‘a’ << std::endl;std::cout << typeid(‘a’).name() << std::endl;return 0;}

Strings: In both Python and C++ a string is a phrase or a series of letters strung together in a group. Our output last week, “Hello World!” is a string. “asdf;lkj” is also a string. A string is indicated by quotation marks around the grouping of letters. In Python these quotations can be single quotations or double quotations as long as the same marks are used for both sides of the string. For instance, in Python: ‘Hello World!’ or “Hello World!” can be used, but ‘Hello World!” and “Hello World!’ cannot. In C++ when typing in strings double quotes MUST be used, as single quote marks are used to indicate a different data type we will learn a little later. The following is an example of string output in Python, followed by the type() method which will print out the data type of whatever parameter was passed in to the parentheses:

print(“Hello Readers!”)print(type(“Hello Readers!”))

The following in the terminal:

python3 data_types.py

results in the following output from the str section:

>> Hello Readers!>> <class ‘str’>

The following is the same string being output in C++.

std::string a = “Hello Readers!”;std::cout << a << std::endl;std::cout << typeid(a).name() << std::endl;

The following in the terminal:

$ g++ -o data_types data_types.cpp$ ./data_types

leads to the output:

>> Hello Readers!>> NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE

Integers (int): int is a data type symbolizing the same thing in both Python and C++: whole numbers. Whenever we are doing math, counting, etc. using whole numbers we will be using integers, indicated by the word int. The following is an example of code in Python outputting an integer:

print(1)print(type(1))

With the following terminal input and output from the int section:

$ python3 data_types.py>> 1>> <class ‘int’>

The following is the same integer output in C++:

std::cout << 4 << std::endl;std::cout << typeid(4).name() << std::endl;

With the terminal input and output from the int section:

$ g++ -o data_types data_types.cpp$ ./data_types>> 4>> i

Notice our use of the std::endl at the end of the output statements. This is the second method we can use to create a new line after whatever output comes before instead of using “\n”. This is useful when our output statement does not require us to include quotation marks, as is the case with integers.

Float: Floating point numbers are another data type found in both programming languages. These are fractional numbers that include a decimal point, such as 3.14 or 32.68. In C++ floating points are defined by a specific maximum precision, between 7 and 9 digits. The following code outputs a float in Python:

print(1.5)print(type(1.5))

Using the terminal:

$ python3 data_types.py>> 1.5>> <class ‘float’>

The following code outputs the same float in C++:

float c = 4.5;std::cout << c << std::endl;std::cout << typeid(c).name() << std::endl;

Using the terminal:

$ g++ -o data_types data_types.cpp$ ./data_types>> 4.5>> f

Double: Here we run into our first data type found in C++ but not Python. This data type is fairly similar to the float, save for one major difference: it is a floating point number with a precision greater than the float data type. In essence a float has 32-bit precision whereas a double has 64-bit precision. The level of precision the programmer wishes to have will be the deciding factor in which data type is used. In C++ the default and most common type when using floating points is the double. The following code outputs a double in C++:

double d = 4.555555555555555555;std::cout << d << std::endl;std::cout << typeid(d).name() << std::endl;

With the terminal:

$ g++ -o data_types data_types.cpp$ ./data_types>> 4.55556>> d

Characters (char): Characters are the second major data type found in C++ but not in Python, though the term character IS used in Python to describe similar things. A character is a single item in a string and can be any single letter, number, or special character surrounded by single quotation marks. Some examples would include: ‘a’, ‘1’, ‘#’, etc. In Python we say that a string, such as “Hello World!” is made up of a grouping of characters, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, etc. however each of these characters, in Python, is still considered to be single character strings. C++ takes this a step further and classifies them in a separate data type altogether, the char. While strings, as mentioned above, are characterized by double quotations, chars are characterized by single quotations. The following code outputs a character in C++:

std::cout << ‘a’ << std::endl;std::cout << typeid(‘a’).name() << std::endl;

with the terminal:

$ g++ -o data_types data_types.cpp$ ./data_types>> a>> c

Boolean (bool): The boolean data type, found in both C++ and Python, is used to answer yes or no questions. A boolean datatype consists of just two possibilities, True or False in Python (with the capitals), and true (1) or false (0) in C++. This data type is generally used when a programmer wants to check for specific conditions, such as “if x is 5”: we will learn more about conditionals in a later volume.

The following code outputs a boolean in Python:

print(True)print(type(True))

Using the terminal:

$ python3 data_types.py>> True>> <class ‘bool’>

The following code outputs the same boolean in C++:

std::cout << true << std::endl;std::cout << typeid(true).name() << std::endl;

Using the terminal:

$ g++ -o data_types data_types.cpp$ ./data_types>> 1>> b

Variables

Programmers often need a way to store some data type for later use; this is true regardless of the programming language being used. These storage containers are called variables. Variables are a way to keep code clean and decrease the possibility of bugs or errors in a program, especially as the program gets larger and more complex. If you are coming from the Python language you will understand this very well. To use a variable the programmer must first declare the variable; this essentially tells the computer that we want to use a specific storage place in memory and that we want to assign that storage space a specific name. For instance, in Python we would declare a variable titled a and assign it the string “Hello Readers!” using the following code:

a = “Hello Readers!”

where a is the title of some space in computer memory and the string is the content we are assigning to that storage space. In python, when declaring a variable we do not have to specify what data type we want to store in that variable as the software running in the background will deduce that automatically. In C++ we are not given the same curtesy (remember, speed over ease of use!). The same variable declaration and content assignment in C++ can be seen in the code below:

#include <iostream>#include <string>int main(){std::string a = “Hello Readers!”;
return 0
}

From this code you can see that in declaring the variable the programmer must also include what data type she/he intends to store in that variable (storage space); the C++ programming language is not capable of deducing the data type. In C++ a variable declaration can be made without assigning it any content immediately — this assigns the storage space a name but leaves it empty for the time being, so that later on in the program the variable can be assigned some content of the declared data type. An example of this can be seen in the code below:

int b;

The code below shows the use of variables in Python using content of varying different data types and outputs the assigned content of each variable (storage space):

a = “Hello Readers!”b = 1c = 1.5d = 1.67426855349e = ‘a’f = Trueg = Falseprint(a,”\n”,b,”\n”,c,”\n”,d,”\n”,e,”\n”,f,”\n”,g)

The following C++ code uses the same or similar content:

#include <iostream> // Used for cin and cout#include <string> // Used to allow us to declare stringsint main(){std::string a = “Hello Readers!”;int b = 1;float c = 1.5;double d = 1.67426855349;char e = ‘a’;bool f = true;bool g = false;std::cout << b << std::endl;std::cout << c << std::endl;std::cout << d << std::endl;std::cout << e << std::endl;std::cout << f << std::endl;std::cout << g << std::endl;return 0;}

Collecting User Input

At some point in most programs a developer needs to collect some sort of input or data from the user; furthermore, you will know from your own experience as a user of varying different programs that in most cases if the program you are using is not interactive in some way it begins to lose the user’s interest quickly or becomes less memorable. That being the case, it is vitally important to understand how to collect some sort of input from the user; today we will touch on the very basics of that.

In Python this is done through another method built directly in to the background software of the programming language. This is done by simply calling the method input() and passing in a parameter within the parentheses that includes some sort of prompt informing the user what they should input. We can use the print() method in conjunction with the input() method if we simply wish to print out whatever input the user gave, such as the code below:

print(input(“What is your name? \n”))

We can also save the user’s input to some variable for use at a later time. Some examples of this can be seen in the code below:

a = input(“Type in a phrase: \n”)b = input(“Type in a whole number: \n”)c = input(“Type in a decimal number: \n”)d = input(“Type in ‘True’ or ‘False’: \n”)

Keep in mind, however, that all input from the user is returned to the program in string format. In the code above when we checked the data type of each of the variables we were given the string output, even in cases where we wanted an integer, float, or boolean. Using the variables above:

print(a, “\n”, type(a))print(b, “\n”, type(b))print(c, “\n”, type(c))print(d, “\n”, type(d))

through the terminal:

$ python3 collecting_input.py>> Type in a phrase
>> I like bacon
>> Type in a whole number:
>> 5
>> Type in a decimal number:
>> 2.3
>> Type in ‘True’ or ‘False’:
>> True
>> I like bacon
>> <class ‘str’>
>> 5
>> <class ‘str’>
>> 2.3
>> <class ‘str’>
>> True
>> <class ‘str’>

This issue can be fixed using Python’s built-in methods: int(), float(), and bool() which simply converts the passed in parameter to the wanted datatype assuming the proper conditions are met. This conversion and the new data type output can be seen in the code below, using the same variables from above:

b = int(b)c = float(c)d = bool(d)print(a, “\n”, type(a))print(b, “\n”, type(b))print(c, “\n”, type(c))print(d, “\n”, type(d))

Using the terminal:

$ python3 collecting_input.py>> Type in a phrase
>> I like bacon
>> Type in a whole number:
>> 5
>> Type in a decimal number:
>> 2.3
>> Type in ‘True’ or ‘False’:
>> True
>> I like bacon
>> <class ‘str’>
>> 5
>> <class ‘int’>
>> 2.3
>> <class ‘float’>
>> True
>> <class ‘bool’>

In C++ a somewhat similar method is used. This method, found in the iostream library using the std keyword (the same library as the cout method), is called cin. When we want to retrieve some sort of data from the user we first send the user a prompt using the cout method. On the next line we indicate that we want to save the user’s input to some variable (which was declared earlier on in the program). Because the variable declaration includes the intended data type we do not need to use a conversion method like we did in Python. However, when working with strings the user input in C++ is collected in a character by character basis. Simply using the std::cin method and assigning the user’s input into the variable a, if the user were to type in “Hello Reader!” the program would only capture and store the ‘H’ character. To get the full string the getline() method would need to be called first, then passed in the parameters std::cin to specify that we want to get the full line of input from the user, followed by the variable name we which to store that line in. An example of this can be seen in the code below:

#include <iostream>#include <string>#include <typeinfo>int main(){std::string a;int b;double c;bool d;std::cout << “Type in a phrase: \n”;getline(std::cin, a);std::cout << a << endl;return 0;
}

When working with other data types, however, this is not required; we simply need to declare a variable, give the user some prompt through the std::cout method, then store the user’s input into the declared variable using the std::cin method. Keep in mind the differences between using the std::cout method and the std::cin method, namely that what we want to output comes after the double left arrows, <<, whereas the variable we want to save our user input to comes after the double right arrows, >>. This can be seen in the code example below:

#include <iostream>#include <string>#include <typeinfo>int main(){std::string a;int b;double c;bool d;std::cout << “Type in a phrase: \n”;getline(std::cin, a);std::cout << “Type in a whole number: \n”;std::cin >> b;std::cout << “Type in a decimal number: \n”;std::cin >> c;std::cout << “Type in ‘True’ or ‘False’: \n”;std::cin >> d;std::cout << a << std::endl;std::cout << typeid(a).name() << std::endl;std::cout << b << std::endl;std::cout << typeid(b).name() << std::endl;std::cout << c << std::endl;std::cout << typeid(c).name() << std::endl;std::cout << d << std::endl;std::cout << typeid(d).name() << std::endl;return 0;}

Thank you for joining me in this week’s installment of Python to C++! I hope you learned as much as I did and I hope to see you again next week when we will learn how to work with numbers and strings in both languages, including basic mathematical operations and breaking down strings into its basic parts. As always, fantastic reader, rep it up and happy coding!

--

--

Daniel Benson
Analytics Vidhya

I am a Data Scientist and writer prone to excitement and passion. I look forward to a future I am able to focus those characteristics into work I love.