Programming C++  «Prev 

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.