Programming C++  «Prev  Next»
Lesson 3 C++ Input
ObjectiveConvert a simple input/output program in C to C++.

Convert C program to C++ program

Take a look at simple input in C++. We will write a program that prompts the user for a value in miles. The program then converts this value to kilometers and prints it out.

Program dissection

Our conversion program uses variables capable of storing integer values and real values, as well as const variables. Notice that in C++, all variables must be declared before they can be used, but unlike in C, they need not be at the head of a block.
The diagram below contains code surrounded by red rectangles which outlines the bullet points below.
C++ Input
  1. The keyword "const" replaces some uses of the "define" preprocessor command to create named literals. Using this type modifier informs the compiler that the initialized value of m_to_k cannot be changed. Thus, it makes m_to_k a symbolic constant.
  2. The new keyword "inline" specifies that a function is to be compiled as inline code, if possible. This avoids function call overhead and is better practice than C's use of define macros. As a rule, inline should be done sparingly and only on short functions. We'll discuss inlining in a later module.
  3. The input stream variable "cin" is the normal standard input. The input operator >>, called the "get from" or "extraction" operator, assigns values from the input stream to a variable.
  4. The value placed in the standard input stream is passed to the convert() function, returned as the number of kilometers, and then printed to the standard output stream.


C++ const and Type Safety

The use of const is highly desirable because it protects a variable from inadvertent change and documents the use of the value. Furthermore, the compiler is at liberty to optimize code connected to constants, for example storing them in read-only high-speed memory. Type-safety is an important property of C++ where compilers are able to perform type checking statically and consequently find bugs that would be difficult to discover at runtime. The narrower the type, the more safety and, frequently, the more efficiency. Integer arithmetic is usually more accurate and faster than floating-point arithmetic. A char or a short take less space than an int or a long.
  1. Implicit type conversions: When an expression contains operands of different built-in types, and no explicit casts are present, the compiler uses built-in standard conversions to convert one of the operands so that the types match. The compiler tries the conversions in a well-defined sequence until one succeeds. If the selected conversion is a promotion, the compiler does not issue a warning. If the conversion is a narrowing, the compiler issues a warning about possible data loss. Whether actual data loss occurs depends on the actual values involved, but we recommend that you treat this warning as an error. If a user-defined type is involved, then the compiler tries to use the conversions that you have specified in the class definition. If it cannot find an acceptable conversion, the compiler issues an error and does not compile the program.
  2. Constants: In pre-Standard C, if you wanted to make a constant, you had to use the preprocessor:
    #define PI 3.14159
    
    Everywhere you used PI, the value 3.14159 was substituted by the preprocessor (you can still use this method in C and C++). When you use the preprocessor to create constants, you place control of those constants outside the scope of the compiler. No type checking is performed on the name PI and you cannot take the address of PI (so you cannot pass a pointer or a reference to PI). PI cannot be a variable of a user-defined type. The meaning of PI lasts from the point it is defined to the end of the file; the preprocessor does not recognize scoping. C++ introduces the concept of a named constant that is just like a variable, except that its value cannot be changed. The modifier const tells the compiler that a name represents a constant. Any data type, built-in or user-defined, may be defined as const. If you define something as const and then attempt to modify it, the compiler will generate an error. You must specify the type of a const, like this:
    const int x = 10;
    
    In Standard C and C++, you can use a named constant in an argument list, even if the argument it fills is a pointer or a reference (for example, you can take the address of a const). A const has a scope, just like a regular variable, so you can hide a const inside a function and be sure that the name will not affect the rest of the program. The const was taken from C++ and incorporated into Standard C, albeit quite differently. In C, the compiler treats a const just like a variable that has a special tag attached that says "Do not change me." When you define a const in C, the compiler creates storage for it, so if you define more than one const with the same name in two different files (or put the definition in a header file), the linker will generate error messages about conflicts. The intended use of const in C is quite different from its intended use in C++.

Simple input Program in C++

//Miles converted to kilometers.

#include <iostream.h>
const double m_to_k = 1.609;
inline double convert(double mi) {
  return (mi * m_to_k);
}
   
main()
{
  double miles;
  do{
    cout << "Input distance in miles: ";
    cin >> miles;
    cout << "\nDistance is " << convert(miles)
    << " km." << endl;
  } while (miles > 0);
 return (0);
}

const double m_to_k = 1.609;

The keyword const replaces some uses of the preprocessor command define to create named literals. Using this type modifier informs the compiler that the initialized value of m_to_k cannot be changed. Thus, it makes m_to_k a symbolic constant.
inline double convert(double mi) {
  return (mi * m_to_k);
}

The new keyword inline specifies that a function is to be compiled as inline code, if possible. This avoids function call overhead and is better practice than C's use of define macros. As a rule, inline should be done sparingly and only on short functions. We will discuss inlining in a later module.

cin >> miles;

The input stream variable cin is the normal standard input. The input operator >>, called the get from or extraction operator, assigns values from the input stream to a variable.

cout << "\nDistance is " << convert(miles)
 << " km." << endl;

The value placed in the standard input stream is passed to the convert() function, returned as the number of kilometers, and then printed to the standard output stream.

Programming Languages

Programming languages are designed independent of specific computer architecture, but they are human creations and follow certain conventions. To ease the translation process, those conventions are much stricter than they are for human languages. When you talk to another person, and you scramble or omit a word or two, your conversation partner will usually still understand what you have to say. Compilers are less forgiving.
For example, if you omit the quotation mark close to the end of the instruction,
if (int_rate > 100) message_box("Interest rate error);

the C++ compiler will get quite confused and complain that it cannot translate an instruction containing this error which is a good thing. If the compiler were to try to guess what you did wrong and try to fix it, it might not guess your intentions correctly. In that case, the resulting program would do the wrong thing with side effects. When a compiler reads programming instructions in a programming language, it will translate them into machine code only if the input follows the language conventions exactly. Just as there are many human languages, there are many programming languages. Consider the instruction
if (int_rate > 100) cout << "Interest rate error";

This is how you must format the instruction in C++. But in Visual Basic (a popular programming language for business applications) the same instruction would be written as
if int_rate > 100 
then System.Console.Write("Interest rate error") 
end if
Compilers are language-specific and the C++ compiler will translate only C++ code, whereas a Visual Basic compiler will reject anything but legal Visual Basic code. For example, if a C++ compiler reads the instruction
if int_rate > 100 then ..., 

it will complain, because the condition of the if statement is not surrounded by parentheses ( ), and the compiler does not expect the word then. The choice of the layout for a language construct such as the if statement is somewhat arbitrary. The designers of different languages make different tradeoffs among readability, easy translation, and consistency with other constructs.

Using IO Stream Exercise

Click the Exercise link below to convert a simple input/output program in C to C++.
Using IO Stream - Exercise

SEMrush Software