Input and output are essential for any computer software, as these are the only means by which the program can communicate with the user. The simplest form of input/output is pure textual, i.e. the application displays in console form, using simple ASCII characters to prompt the user for inputs, which are supplied using the keyboard.

There are many ways for a program to gain input and output, including

File i/o, that is, reading and writing to files

Console i/o, reading and writing to a console window, such as a terminal in UNIX-based operating systems or a DOS prompt in Windows.

Network i/o, reading and writing from a network device

String i/o, reading and writing treating a string as if it were the input or output device

While these may seem unrelated, they work very similarly. In fact, operating systems that follow the POSIX specification deal with files, devices, network sockets, consoles, and many other things all with one type of handle, a file descriptor. However, low-level interfaces provided by the operating system tend to be difficult to use, so C++, like other languages, provide an abstraction to make programming easier. This abstraction is the stream.

ASCII is a character-encoding scheme based on the ordering of the English alphabet. The 95 ASCII graphic characters numbered from 0x20 to 0x7E (32 to 126 decimal), also known as the printable characters, represent letters, digits, punctuation marks, and a few miscellaneous symbols. The first 32 ASCII characters, from 0x00 to 0x20, are known as control characters. The space character, that denotes the space between words, as produced by the space-bar of a keyboard, represented by code 0x20 (hexadecimal), is considered a non-printing graphic (or an invisible graphic) rather than a control character.

A stream is a type of object from which we can take values, or to which we can pass values. This is done transparently in terms of the underlying code that demonstrates the use of the std::cout stream, known as the standard output stream.

Almost all input and output one ever does can be modeled very effectively as a stream. Having one common model means that one only has to learn it once. If you understand streams, you know the basics of how to output to files, the screen, sockets, pipes, and anything else that may come up.

A stream is an object that allows one to push data in or out of a medium, in order. Usually a stream can only output or can only input. It is possible to have a stream that does both, but this is rare. One can think of a stream as a car driving along a one-way street of information. An output stream can insert data and move on. It (usually) cannot go back and adjust something it has already written. Similarly, an input stream can read the next bit of data and then wait for the one that comes after it. It does not skip data or rewind and see what it had read five minutes ago.

The semantics of what a stream's read and write operations do depend on the type of stream. In the case of a file, an input file stream reads the file's contents in order without rewinding, and an output file stream writes to the file in order. For a console stream, output means displaying text, and input means getting input from the user via the console. If the user has not inputted anything, then the program blocks, or waits, for the user to enter in something.

To do:
Remember to complete with the String Stream class and include the various io stream format flags.

iostream is a header file used for input/output. It is part of the C++ standard library. The name stands for Input/Output Stream. In C++ there is no special syntax for streaming data input or output. Instead, these are combined as a library of functions. Like we have seen with the C Standard Library use of <cstdio> header, iostream provides basic OOP services for I/O.

The iostream automatically defines and uses a few standard objects:

cin, an object of the istream class that reads data from the standard input device.

cout, an object of the ostream class, which displays data to the standard output device.

cerr, another object of the ostream class that writes unbuffered output to the standard error device.

clog, like cerr, but uses buffered output.

for sending data to and from the standard streams input, output, error (unbuffered), and error (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace.

Standard input, output, and error

The most common streams one uses are cout, cin, and cerr (pronounced "c out", "c in", and "c err(or)", respectively). They are defined in the header <iostream>. Usually, these streams read and write from a console or terminal. In UNIX-based operating systems, such as Linux and Mac OS X, the user can redirect them to other files, or even other programs, for logging or other purposes. They are analogous to stdout, stdin, and stderr found in C. cout is used for generic output, cin is used for input, and cerr is used for printing errors. (cerr typically goes to the same place as cout, unless one or both is redirected, but it is not buffered and allows the user to fine-tune which parts of the program's output is redirected where.)

It is always a good idea to end your output with a blank line, so as to not mess up with user's terminals.

As seen in the "Hello, World!" program, we direct the output to std::cout. This means that it is a member of the standard library. For now, don't worry about what this means; we will cover the library and namespaces in later chapters.

What you do need to remember is that, in order to use the output stream, you must include a reference to the standard IO library, as shown here:

#include<iostream>

This opens up a number of streams, functions and other programming devices that we can now use. For this section, we are interested in two of these; std::cout and std::endl.

Once we have referenced the standard IO library, we can use the output stream very simply. To use a stream, give its name, then pipe something in or out of it, as shown:

std::cout<<"Hello, World!";

The << operator feeds everything to the right of it into the stream. We have essentially fed a text object into the stream. That's as far as our work goes; the stream now decides what to do with that object. In the case of the output stream, it's printed on-screen.

We're not limited to only sending a single object type to the stream, nor indeed are we limited to one object a time. Consider the examples below:

std::cout<<"Hello, "<<"Joe"<<std::endl;std::cout<<"The answer to life, the universe and everything is "<<42<<std::endl;

As can be seen, we feed in various values, separated by a pipe character. The result comes out something like:

Hello, Joe
The answer to life, the universe and everything is 42

You will have noticed the use of std::endl throughout some of the examples so far. This is a special manipulator, which not only outputs a newline character but also calls os.flush().

What would be the use of an application that only ever outputted information, but didn't care about what its users wanted? Minimal to none. Fortunately, inputting is as easy as outputting when you're using the stream.

The standard input stream is called std::cin and is used very similarly to the output stream. Once again, we instantiate the standard IO library:

#include<iostream>

This gives us access to std::cin (and the rest of that class). Now, we give the name of the stream as usual, and pipe output from it into a variable. A number of things have to happen here, demonstrated in the example below:

#include<iostream>intmain(intiArgc,chara_chArgv[]){intiA;std::cout<<"Hello! How old are you? ";std::cin>>iA;std::cout<<"You're really "<<iA<<" years old?"<<std::endl;return0;}

We instantiate the standard IO library as usual, and call our main function in the normal way. Now we need to consider where the user's input goes. This calls for a variable (discussed in a later chapter) that we declare as being called a.

Next, we send some output, asking the user for their age. The real input happens now; everything the user types until they hit Enter is going to be stored in the input stream. We pull this out of the input stream and save it in our variable.

Finally, we output the user's age, piping the contents of our variable into the output stream.

Note: You will notice that, if anything other than a whole number is entered, the program will crash. This is due to the way in which we set up our variable. Don't worry about this for now; we will cover variables later on.

The following program inputs two numbers from the user and prints their sum:

#include<iostream>intmain(){intiNumber1,iNumber2;std::cout<<"Enter number 1: ";std::cin>>iNumber1;std::cout<<"Enter number 2: ";std::cin>>iNumber2;std::cout<<"The sum of "<<iNumber1<<" and "<<iNumber2<<" is "<<iNumber1+iNumber2<<".\n";return0;}

Just like std::cout that represents the standard output stream, the C++ library provides (and the iostream header declares) the object std::cin representing standard input, which usually gets input from the keyboard. The statement:

std::cin>>iNumber1;

uses the extraction operator (>>) to get an integer input from the user. When used to input integers, any leading whitespace is skipped, a sequence of valid digits optionally preceded by a + or - sign is read and the value stored in the variable. Any remaining characters in the user input are not consumed. These would be considered next time some input operation is performed.

If you want the program to use a function from a specific namespace, normally you must specify which namespace the function is in. The above example calls to cout, which is a member of the std namespace (hence std::cout). If you want a program to specifically use the std namespace for an identifier, which essentially removes the need for all future scope resolution (e.g. std::), you could write the above program like this:

#include<iostream>usingnamespacestd;intmain(){intiNumber1,iNumber2;cout<<"Enter number 1: ";cin>>iNumber1;cout<<"Enter number 2: ";cin>>iNumber2;cout<<"The sum of "<<iNumber1<<" and "<<iNumber2<<" is "<<iNumber1+iNumber2<<".\n";return0;}

Please note that 'std' namespace is the namespace defined by standard C++ library.

A manipulator is a function that can be passed as an argument to a stream in different circumstances. For example, the manipulator 'hex' will cause the stream object to format subsequent integer input to the stream in hexadecimal instead of decimal. Likewise, 'oct' results in integers displaying in octal, and 'dec' reverts back to decimal.

There are many manipulators that can be used in conjunction with streams to simplify the formatting of input. For example, 'setw()' sets the field width of the data item next displayed. Used in conjunction with 'left' and 'right'(that set the justification of the data), 'setw' can easily be used to create columns of data.

The data in the top row display at the right of the columns created by 'setw', while in the next row, the data is left justified in the column. Please note the inclusion of a new library 'iomanip'. Most formatting manipulators require this library.

Here are some other manipulators and their uses:

Manipulator

Function

boolalpha

displays boolean values as 'true' and 'false' instead of as integers.

noboolalpha

forces bools to display as integer values

showuppercase

converts strings to uppercase before displaying them

noshowuppercase

displays strings as they are received, instead of in uppercase

fixed

forces floating point numbers to display with a fixed number of decimal places

Most stream objects, including 'cout' and 'cin', have an area in memory where the information they are transferring sits until it is asked for. This is called a 'buffer'. Understanding the function of buffers is essential to mastering streams and their use.

The inputs are given separately, with a hard return between them. '>' denotes user input.

Execution 2

>74 27
Number1: 74
Number2: 27

The inputs are entered on the same line. They both go into the 'cin' stream buffer, where they are stored until needed. As 'cin' statements are executed, the contents of the buffer are read into the appropriate variables.

Execution 3

>74 27 56
Number1: 74
Number2: 27

In this example, 'cin' received more input than it asked for. The third number it read in, 56, was never inserted into a variable. It would have stayed in the buffer until 'cin' was called again. The use of buffers can explain many strange behaviors that streams can exhibit.

Notice how all three numbers were entered at the same time in one line, but the stream only pulled them out of the buffer when they were asked for. This can cause unexpected output, since the user might accidentally put an extra space into his input. A well written program will test for this type of unexpected input and handle it gracefully.

ios is a header file in the C++ standard library that defines several types and functions basic to the operation of iostreams. This header is typically included automatically by other iostream headers. Programmers rarely include it directly.

The template class describes the storage and member functions common to both input streams (of template class basic_istream) and output streams (of template class basic_ostream) that depend on the template parameters.

fpos

The template class describes an object that can store all the information needed to restore an arbitrary file-position indicator within any stream.

ios_base

The class describes the storage and member functions common to both input and output streams that do not depend on the template parameters.

With cout and cin, we can do basic communication with the user. For more complex io, we would like to read from and write to files. This is done with file stream classes, defined in the header <fstream>. ofstream is an output file stream, and ifstream is an input file stream.

Files

To open a file, one can either call open on the file stream or, more commonly, use the constructor. One can also supply an open mode to further control the file stream. Open modes include

ios::app Leaves the file's original contents and appends new data to the end.

ios::out Outputs new data in the file, removing the old contents. (default for ofstream)

ios::in Reads data from the file. (default for ifstream)

Example

// open a file called Test.txt and write "HELLO, HOW ARE YOU?" to it#include<fstream>usingnamespacestd;intmain(){ofstreamfile1;file1.open("file1.txt",ios::app);file1<<"This data will be appended to the file file1.txt\n";file1.close();ofstreamfile2("file2.txt");file2<<"This data will replace the contents of file2.txt\n";return0;}

The call to close() can be omitted, if you do not care about the return value (whether it succeeded); the destructors will call close when the object goes out of scope.

If an operation (e.g. opening a file) was unsuccessful, a flag is set in the stream object. You can check the flags' status using the bad() or fail() member functions, which return a boolean value. The stream object doesn't throw any exceptions in such a situation; hence manual status check is required. See reference for details on bad() and fail().

It is often useful to have your own classes' instances compatible with the stream framework. For instance, if you defined the class Foo like this:

classFoo{public:Foo():m_iX(1),m_iY(2){}intm_iX,m_iY;};

You will not be able to pass its instance to cout directly using the '<<' operator, because it is not defined for these two objects (Foo and ostream). What needs to be done is to define this operator and thus bind the user-defined class with the stream class.

This is a small example that rounds a number to a string, a function called RoundToString. Figures may have trailing zeros, those that would be expected to disappear using a number format.

The constant class contains repeating constants that should exist only once in the code so that to avoid inadvertent changes. (If the one constant is changed inadvertently, it is most likely to be seen, as it is used at several locations.)

The code was first cross-compiled by the JAVA TO C++ CONVERTER of Tangible Software Solutions. Parts may have a copyright notice requirement that prevents inclusion in this work you can get yourself the code for the StringConverter at that location.

Here is the relevant code and its call. You are invited to write a shorter version that gives the same result.

#pragma once#include<string>namespacecommon{/// <summary>/// Class that comprises of constant values and recurring algorithms./// /// @author Saban/// ///</summary>classCommon{/// <summary>/// Determines, if the character is trimmable or not./// </summary>/// <param name="chCHARACTER">Character to be checked</param>/// <param name="chTRIM">/// Trim character that defaults to a space/// </param>/// <param name="bIS_NUMERIC">/// If numeric, zeros are also considered as trimmable characters/// </param>/// <returns>Whether the character is trimmable or not</returns>staticboolIsTrimmable(charconstchCHARACTER,charconstchTRIM=SPACE,boolconstbIS_NUMERIC=true);public:/// <summary>Carriage return constant</summary>//static char const CARRIAGE_RETURN = '\r';/// <summary>Constant of comma or decimal point in German</summary>staticcharconstCOMMA=',';/// <summary>Dash or minus constant</summary>staticcharconstDASH='-';/// <summary>/// The exponent sign in a scientific number, or the letter e./// </summary>staticcharconstEXPONENT='e';/// <summary>The full stop or period</summary>staticcharconstPERIOD='.';/// <summary>Space constant</summary>staticcharconstSPACE=' ';/// <summary>Space constant</summary>staticcharconstZERO='0';/// <summary>//// Value under which the double should switch to fixed-point./// </summary>staticdoubleconstVERY_LARGE;/// <summary>//// Value above which the double should switch to fixed-point./// </summary>staticdoubleconstNEARLY_ZERO;/// <summary>/// The zero string constant used at several places/// </summary>staticstringconststrZERO;/// <summary>/// Trims the trim character from left and right of the value./// </summary>/// <param name="strVALUE">Value to be trimmed</param>/// <param name="chTRIM">/// Trim character that defaults to a space/// </param>/// <returns>Trimmed string</returns>staticstringconst&Trim(stringconst&strVALUE,charconstchTRIM=Common::SPACE);/// <summary>/// Trims the trim character from left the value./// </summary>/// <param name="strVALUE">Value to be trimmed</param>/// <param name="chTRIM">/// Trim character that defaults to a space/// </param>/// <returns>Trimmed string</returns>staticstringconst&TrimLeft(stringconst&strVALUE,charconstchTRIM=Common::SPACE);/// <summary>/// Trims the trim character from right of the value./// </summary>/// <param name="strVALUE">Value to be trimmed</param>/// <param name="chTRIM">/// Trim character that defaults to a space/// </param>/// <returns>Trimmed string</returns>staticstringconst&TrimRight(stringconst&strVALUE,charconstchTRIM=Common::SPACE);};// class Common}

The Math class is an enhancement to the <math.h> library and contains the rounding calculations.

Math.cpp:

#include"StdAfx.h"#include<string>namespacecommon{stringconstMaths::strZEROS="000000000000000000000000000000000";byteMaths::CalculateMissingSignificantZeros(byteconstySIGNIFICANTS_AFTER,charconstchSEPARATOR,doubleconstdVALUE,stringconststrMANTISSA){// Existing significants after decimal separator arebyteconstyAFTER=FindSignificantsAfterDecimal(chSEPARATOR,strMANTISSA);// Number of digits to add arebyteconstyZEROS=ySIGNIFICANTS_AFTER-((yAFTER==0)?1:yAFTER);return((yZEROS>=0)?yZEROS:0);}byteMaths::FindDecimalSeparatorPosition(stringconst&strVALUE){byteconstySEPARATOR_AT=(byte)strVALUE.find(Common::PERIOD);return(ySEPARATOR_AT>-1)?ySEPARATOR_AT:(byte)strVALUE.find(Common::COMMA);}byteMaths::FindFirstNonZeroDigit(doubleconstdVALUE){returnFindFirstNonZeroDigit(StringConverter::ToString<double,StringConverter::DIGITS>(dVALUE));}byteMaths::FindFirstNonZeroDigit(stringconst&strVALUE){// Find the position of the first non-zero digit:byteyNonZeroAt=0;for(;(yNonZeroAt<(byte)strVALUE.length())&&((strVALUE[yNonZeroAt]==Common::DASH)||(strVALUE[yNonZeroAt]==Common::PERIOD)||(strVALUE[yNonZeroAt]==Common::ZERO));yNonZeroAt++);returnyNonZeroAt;}byteMaths::FindSignificantDigits(byteconstySIGNIFICANTS_AFTER,charconstchSEPARATOR,doubleconstdVALUE){if(dVALUE==0)return0;else{//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':stringstrMantissa=FindMantissa(TestCommons::SIGNIFICANTS,chSEPARATOR,StringConverter::ToString<double,StringConverter::DIGITS>(dVALUE));if(dVALUE==static_cast<long>(dVALUE)){strMantissa=strMantissa.substr(0,strMantissa.find(Common::COMMA));}strMantissa=RetrieveDigits(chSEPARATOR,strMantissa);returnstrMantissa.substr(FindFirstNonZeroDigit(strMantissa)).length();}}byteMaths::FindSignificantsAfterDecimal(byteconstySIGNIFICANTS_BEFORE,byteconstySIGNIFICANT_DIGITS){byteconstyAFTER_DECIMAL=ySIGNIFICANT_DIGITS-ySIGNIFICANTS_BEFORE;return(yAFTER_DECIMAL>0)?yAFTER_DECIMAL:0;}byteMaths::FindSignificantsAfterDecimal(charconstchSEPARATOR,doubleconstdVALUE){if(dVALUE==0)return1;else{//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':stringstrValue=StringConverter::ToString<double,StringConverter::DIGITS>(dVALUE);byteconstySEPARATOR_AT=(byte)strValue.find(chSEPARATOR);if(ySEPARATOR_AT>-1){strValue=strValue.substr(ySEPARATOR_AT+1);}shortconstsE_AT=strValue.find(Common::EXPONENT);if(sE_AT>0)strValue=strValue.substr(0,sE_AT);longlValue=StringConverter::FromString<long,StringConverter::DIGITS>(strValue);if(abs(dVALUE)<1){return(byte)StringConverter::ToString<long,StringConverter::DIGITS>(lValue).length();}elseif(lValue==0)return0;else{strValue="0."+strValue;return(byte)(strValue.length()-2);}}}byteMaths::FindSignificantsBeforeDecimal(charconstchSEPARATOR,doubleconstdVALUE){stringconststrVALUE=StringConverter::ToString<double,StringConverter::DIGITS>(dVALUE);// Return immediately, if result is clear: Special handling at// crossroads of floating point and exponential numbers:if((dVALUE==0)||(abs(dVALUE)>=Common::NEARLY_ZERO)&&(abs(dVALUE)<1)){return0;}elseif((abs(dVALUE)>0)&&(abs(dVALUE)<Common::NEARLY_ZERO)){return1;}else{bytesignificants=0;// Significant digits to the right of decimal separator:for(bytes=0;s<(byte)strVALUE.length();s++){if((strVALUE[s]==chSEPARATOR)||(strVALUE[s]==Common::EXPONENT)){break;}elseif(strVALUE[s]!=Common::DASH)significants++;}returnsignificants;}}byteMaths::FindSignificantsAfterDecimal(charconstchSEPARATOR,stringconststrVALUE){size_tconstCOMMA_AT=strVALUE.find(chSEPARATOR);size_tconstLENGTH=strVALUE.length();// Existing digits after decimal separator arebyteyAfter=0;// Existing significants after decimal separator may start at the first// non-zero digit:if(StringConverter::FromString<double,5>(strVALUE.substr(0,COMMA_AT))==0){stringstrRightOf=Common::TrimLeft(strVALUE.substr(COMMA_AT+1));yAfter=strRightOf.length();}elseyAfter=(COMMA_AT<string::npos)?LENGTH-1-COMMA_AT:0;returnyAfter;}doubleMaths::Power(shortconstsBASIS,shortconstsEXPONENT){if(sBASIS==0)return(sEXPONENT!=0)?1:0;else{if(sEXPONENT==0)return1;else{// The Math method power does change the least significant // digits after the decimal separator and is therefore useless.doubleresult=1;if(sEXPONENT>0){for(shorts=0;s<sEXPONENT;s++)result*=sBASIS;}elseif(sEXPONENT<0){for(shorts=sEXPONENT;s<0;s++)result/=sBASIS;}returnresult;}}}doubleMaths::Round(byteconstyDIGITS,charconstchSEPARATOR,doubleconstdVALUE){if(dVALUE==0)return0;else{boolbIsScientific=false;doubleconstdCONSTANT=Power(10,yDIGITS);if((abs(dVALUE)<Common::NEARLY_ZERO)||(abs(dVALUE)>=Common::VERY_LARGE)){bIsScientific=true;}shortconstsEXPONENT=FindExponent(dVALUE,chSEPARATOR,bIsScientific);shortsExponent=sEXPONENT;// Determine the correcting power:shortsPower=sExponent;if(sEXPONENT==0){sPower=FindExponent(dVALUE,chSEPARATOR,HasDecimals(dVALUE));}doubledValue1=dVALUE*dCONSTANT*pow(10.,-sPower);stringconststrE_SIGN=(sExponent<0)?StringConverter::ToString<char,StringConverter::DIGITS>(Common::DASH):"";if(sExponent!=0){sExponent=static_cast<short>(abs(sExponent));dValue1=Round(dValue1);}elsedValue1=Round(dValue1)/dCONSTANT/pow(10.,-sPower);// Power method cannot be used, as the exponentiated number may// exceed the maximal long value.sExponent-=Signum(sEXPONENT)*(FindSignificantDigits(yDIGITS,chSEPARATOR,dValue1)-1);if(sEXPONENT!=0){//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':stringstrValue=StringConverter::ToString<double,StringConverter::DIGITS>(dValue1);//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':strValue=strValue.substr(0,FindDecimalSeparatorPosition(strValue))+Common::EXPONENT+strE_SIGN+StringConverter::ToString<short,StringConverter::DIGITS>(sExponent);dValue1=StringConverter::FromString<double,5>(strValue);}returndValue1;}}doubleMaths::Round(doubleconstdValue){return(double)(longlong)(dValue+.5);}shortMaths::FindExponent(doubleconstdVALUE,charconstchSEPARATOR,boolconstbSCIENTIFIC){//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':return(short)StringConverter::FromString<short,StringConverter::DIGITS>(FindExponent(StringConverter::ToString<double,StringConverter::DIGITS>(dVALUE),chSEPARATOR,bSCIENTIFIC));}stringMaths::FindExponent(stringconst&strVALUE,charconstchSEPARATOR,boolconstbSCIENTIFIC){if(StringConverter::FromString<double,StringConverter::DIGITS>(strVALUE)==0){returnCommon::strZERO;}shortconstsE_AT=strVALUE.find(Common::EXPONENT);shortsExponent=0;if(sE_AT<0){// If all numbers are to be considered scientific, such as// 1 = 1.0000e0…if(bSCIENTIFIC){// Find the exponent by counting leading zeros:byteconstySEPARATOR_AT=strVALUE.find(chSEPARATOR);if(ySEPARATOR_AT>-1){stringconststrAFTER=strVALUE.substr(ySEPARATOR_AT+1);sExponent=0;for(;sExponent<(short)strAFTER.length();sExponent++){if((strAFTER[sExponent]>='1')&&(strAFTER[sExponent]<='9')){sExponent*=-1;break;}}}}elsereturnCommon::strZERO;}else{sExponent=(short)StringConverter::FromString<double,StringConverter::DIGITS>(strVALUE.substr(sE_AT+1));}returnStringConverter::ToString<short,StringConverter::DIGITS>(sExponent);}stringMaths::FindMantissa(byteconstyDIGITS,charconstchSEPARATOR,conststring&strVALUE){byteyDigits=yDIGITS;shortconstsE_AT=strVALUE.find(Common::EXPONENT);stringstrValue=strVALUE;// Remove lagging insignificant zeros, if any:if(sE_AT==-1){if(StringConverter::FromString<short,3>(strValue.substr(0,2))==0){byteyPosition=2;for(;(yPosition<(byte)strValue.length())&&((strValue[yPosition]==Common::PERIOD)||(strValue[yPosition]==Common::ZERO));yPosition++);yDigits+=yPosition;strValue=strValue.substr(0,yDigits);}}elsestrValue=Common::TrimRight(strValue.substr(0,sE_AT));if(StringConverter::FromString<double,StringConverter::DIGITS>(strValue)==0){strValue=RemoveInsignificants(yDIGITS,strValue);}elsestrValue=RemoveInsignificants(yDigits,strValue);if(FindDecimalSeparatorPosition(strValue)==-1){returnstrValue+".0";}elsereturnstrValue;}stringMaths::RemoveInsignificants(byteconstyDIGITS,stringconst&strVALUE){byteconstyCHARACTERS=yDIGITS+((FindDecimalSeparatorPosition(strVALUE)<string::npos)?1:0)+((strVALUE[0]==Common::DASH)?((strVALUE[1]==Common::ZERO)?2:1):((strVALUE[0]==Common::ZERO)?1:0));returnstrVALUE.substr(0,yCHARACTERS);}stringMaths::RetrieveDigits(charconstchSEPARATOR,conststring&strNUMBER){stringstrNumber=strNUMBER;shortconstsE_AT=strNumber.find(Common::EXPONENT);// Strip off exponent part, if it exists:if(sE_AT>-1)strNumber=strNumber.substr(0,sE_AT);//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString'://JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'replace':returnStringConverter::Replace(StringConverter::Replace(strNumber,StringConverter::ToString<char,1>(Common::DASH),""),StringConverter::ToString<char,1>(chSEPARATOR),"");}stringMaths::RoundToString(byteconstySIGNIFICANT_DIGITS,charconstchSEPARATOR,doubledValue){// Number of significants that *are* before the decimal separator://JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':byteconstySIGNIFICANTS_BEFORE=FindSignificantsBeforeDecimal(chSEPARATOR,dValue);// Number of decimals that *should* be after the decimal separator:byteconstySIGNIFICANTS_AFTER=FindSignificantsAfterDecimal(ySIGNIFICANTS_BEFORE,ySIGNIFICANT_DIGITS);byteconstyDIGITS=(dValue!=0)?ySIGNIFICANTS_BEFORE+ySIGNIFICANTS_AFTER:3/* = 0.0 */;// Round to the specified number of digits after decimal separator:doubleconstdROUNDED=Maths::Round(ySIGNIFICANTS_AFTER,chSEPARATOR,dValue);//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':stringconststrEXPONENT=FindExponent(StringConverter::ToString<double,StringConverter::DIGITS>(dROUNDED));//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':stringconststrMANTISSA=FindMantissa(TestCommons::SIGNIFICANTS,chSEPARATOR,StringConverter::ToString<double,StringConverter::DIGITS>(dROUNDED));doubleconstdMANTISSA=StringConverter::FromString<double,TestCommons::SIGNIFICANTS>(strMANTISSA);StringBuilder*pRESULT=newStringBuilder(strMANTISSA);// Determine the significant digits in this number:byteconstySIGNIFICANTS=FindSignificantDigits(ySIGNIFICANTS_AFTER,chSEPARATOR,dMANTISSA);// Add lagging zeros, if necessary:if(ySIGNIFICANTS<=ySIGNIFICANT_DIGITS){if(ySIGNIFICANTS_AFTER!=0){if(dValue!=0){pRESULT->Append(strZEROS.substr(0,CalculateMissingSignificantZeros(ySIGNIFICANTS_AFTER,chSEPARATOR,dMANTISSA,strMANTISSA)));}}else{// Cut off the decimal separator & after decimal digits://JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':byteconstyDECIMAL=pRESULT->Find(StringConverter::ToString<char,StringConverter::DIGITS>(chSEPARATOR));if(yDECIMAL>-1)pRESULT->SetLength(yDECIMAL);}}elseif(ySIGNIFICANTS_BEFORE>ySIGNIFICANT_DIGITS){dValue/=Power(10,ySIGNIFICANTS_BEFORE-ySIGNIFICANT_DIGITS);dValue=Round(dValue);byteconstyDIGITS=ySIGNIFICANT_DIGITS+((dValue<0)?1:0);//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':stringconststrVALUE=StringConverter::ToString<double,StringConverter::DIGITS>(dValue).substr(0,yDIGITS);pRESULT->SetLength(0);pRESULT->Append(strVALUE+strZEROS.substr(0,ySIGNIFICANTS_BEFORE-ySIGNIFICANT_DIGITS));}if(StringConverter::FromString<double,StringConverter::DIGITS>(strEXPONENT)!=0){pRESULT->Append(Common::EXPONENT+strEXPONENT);}//JAVA TO C++ CONVERTER TODO TASK: No native C++ equivalent to 'ToString':returnpRESULT->ToString();}// public static String RoundToString(…)}

Math.h:

#pragma once#include<string>#include<cmath>/// namespacecommon{/// <summary>/// Class for special mathematical calculations./// ATTENTION: Should not depend on any other class except Java libraries!/// @author Saban///</summary>classMaths{private:/// <summary>The string of zeros</summary>staticstringconststrZEROS;/// <summary>/// Determines how many zeros are to be appended after the decimal/// digits./// </summary>/// <param name="ySIGNIFICANTS_AFTER">/// Requested significant digits after decimal/// </param>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// </param>/// <param name="dVALUE">Rounded number</param>/// <param name="strMANTISSA">/// Current string where missing digits are to be determined/// </param>/// <returns>Requested value</returns>staticbyteCalculateMissingSignificantZeros(byteconstySIGNIFICANTS_AFTER,charconstchSEPARATOR,doubleconstdVALUE,stringconststrMANTISSA="");/// <summary>/// Finds the decimal position language-independently./// </summary>/// <param name="strVALUE">/// Value to be searched for the decimal separator/// </param>/// <returns>/// The position of the decimal separator or string::npos,/// if no decimal separator has been found./// </returns>staticbyteFindDecimalSeparatorPosition(stringconst&strVALUE);/// <summary>/// Finds the first non-zero decimal position./// </summary>/// <param name="dVALUE">/// Value to be searched for the decimal position/// </param>/// <returns>The first non-zero decimal position</returns>staticbyteFindFirstNonZeroDigit(doubleconstdVALUE);/// <summary>/// Finds the first non-zero decimal position./// </summary>/// <param name="strVALUE">/// Value to be searched for the decimal position/// </param>/// <returns>The first non-zero decimal position</returns>staticbyteFindFirstNonZeroDigit(stringconst&strVALUE);/// <summary>/// Calculates the number of all significant digits (without the sign/// and the decimal separator)./// </summary>/// <param name="ySIGNIFICANTS_AFTER">/// Number of decimal places after the separator</param>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="dVALUE">/// Value where the digits are to be counted/// </param>/// <returns>Number of significant digits</returns>staticbyteFindSignificantDigits(byteconstySIGNIFICANTS_AFTER,charconstchSEPARATOR,doubleconstdVALUE);/// <summary>/// Determines the number of significant digits after the decimal/// separator knowing the total number of significant digits and the/// number before the decimal separator./// </summary>/// <param name="ySIGNIFICANTS_BEFORE">/// Number of significant digits before separator/// </param>/// <param name="ySIGNIFICANT_DIGITS">/// Number of all significant digits/// </param>/// Number of significant decimals after the separator/// </returns>staticbyteFindSignificantsAfterDecimal(byteconstySIGNIFICANTS_BEFORE,byteconstySIGNIFICANT_DIGITS);/// <summary>/// Finds the significant digits after the decimal separator of a/// mantissa./// </summary>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="dVALUE">Value to be scrutinised</param>/// <returns>/// Number of insignificant zeros after decimal separator./// </returns>staticbyteFindSignificantsAfterDecimal(charconstchSEPARATOR,doubleconstdVALUE);/// <summary>/// Finds the significant digits after the decimal separator of a/// mantissa./// </summary>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="strVALUE">Value to be scrutinised</param>/// <returns>/// Number of insignificant zeros after decimal separator./// </returns>staticbyteFindSignificantsAfterDecimal(charconstchSEPARATOR,stringconststrVALUE);/// <summary>/// Determines the number of digits before the decimal point.</summary>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="dVALUE">Value to be scrutinised</param>/// <returns>Number of digits before the decimal separator</returns>staticbyteFindSignificantsBeforeDecimal(charconstchSEPARATOR,doubleconstdVALUE);/// <summary>/// Returns the exponent part of the double number.</summary>/// <param name="dVALUE">/// Value of which the exponent is of interest/// </param>/// <param name="chSEPARATOR">Decimal separator</param>/// <param name="bSCIENTIFIC">/// If true, the number is considered in scientific notation of the form/// 9.999e999 (like 1 = 1.0e0 or 0.124 = 1.24e-1)./// </param>/// <returns>Exponent of the number or zero.</returns>staticshortFindExponent(doubleconstdVALUE,charconstchSEPARATOR=Common::PERIOD,boolconstbSCIENTIFIC=false);/// <summary>/// Finds the exponent of a number.</summary>/// <param name="strVALUE">/// Value where an exponent is to be searched/// </param>/// <param name="chSEPARATOR">Decimal separator</param>/// <param name="bSCIENTIFIC">/// If true, the number is considered in scientific notation of the form/// 1 = 1.0e0 or 0.124 = 1.24e-1./// </param>/// <returns>Exponent, if it exists, or "0"</returns>staticstringFindExponent(stringconst&strVALUE,charconstchSEPARATOR=Common::PERIOD,boolconstbSCIENTIFIC=false);/// <summary>/// Finds the mantissa of a number.</summary>/// <param name="yDIGITS">/// Number of all digits/// </param>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="strVALUE">/// Value where the mantissa is to be found/// </param>/// <returns>Mantissa of the number</returns>staticstringFindMantissa(byteconstyDIGITS,charconstchSEPARATOR,stringconst&strVALUE);/// <summary>/// Removes all insignificant digits.</summary>/// <param name="yDIGITS">/// Number of significant digits/// </param>/// <returns>Number with the requested number of digits</returns>staticstringRemoveInsignificants(byteconstyDigits,stringconst&strVALUE);/// <summary>/// Retrieves the digits of the value without decimal separator or/// sign./// </summary>/// <param name="chSEPARATOR"></param>/// <param name="strNUMBER">Mantissa to be scrutinised</param>/// <returns>The digits only</returns>staticstringRetrieveDigits(charconstchSEPARATOR,stringconst&strNUMBER);public:/// <summary>/// Determines whether the number has decimal places after /// the separator or not./// </summary>/// <param name="VALUE"></param>/// <returns>true, if it has decimals and false otherwise.</returns>template<classT>staticboolHasDecimals(constTVALUE){return((VALUE-(longlong)VALUE)!=0);}/// <summary>/// Calculates the power of the base to the exponent without changing/// the least-significant digits of a number./// </summary>/// <param name="BASIS"></param>/// <param name="EXPONENT"></param>/// <returns>BASIS to power of EXPONENT</returns>staticdoublePower(shortconstsBASIS,shortconstsEXPONENT);/// <summary>/// Rounds a number to the decimal places.</summary>/// <param name="yDIGITS">Number of all decimal places</param>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="dVALUE">Number to be rounded</param>/// <returns>Rounded number to the requested decimal places</returns>staticdoubleRound(byteconstyDIGITS,charconstchSEPARATOR,doubleconstdVALUE);/// <summary>/// Replacement for Math.round(double) of Java.</summary>/// <param name="dValue">Number to be rounded</param>/// <returns>Rounded number to the requested decimal places</returns>staticdoubleRound(doubleconstdVALUE);/// <summary>Signum function</summary>/// <param name="number">Value to be scrutinised</param>/// <returns>Sign of the number</returns>template<classT>staticbyteSignum(Tnumber){return(number<T(0))?T(-1):(number>T(0));}/// <summary>/// Rounds to a fixed number of significant digits.</summary>/// <param name="ySIGNIFICANT_DIGITS">/// Requested number of significant digits/// </param>/// <param name="chSEPARATOR">/// Language-specific decimal separator/// </param>/// <param name="dValue">Number to be rounded</param>/// <returns>Rounded number</returns>staticstringRoundToString(byteconstySIGNIFICANT_DIGITS,charconstchSEPARATOR,doubledValue);};// class Maths}

#pragma oncenamespacecommon{classStringBuilder{private:stringstrMain;public:/// <summary>/// Standard constructor/// </summary>StringBuilder();/// <summary>/// Constructor/// </summary>/// <param name="strSUBJECT">Value to be used</param>StringBuilder(stringconst&strSUBJECT);/// <summary>/// Finds the search string inside itself./// </summary>/// <param name="strSEARCH">Value to be used</param>/// <returns>/// The position of the searched text or -1, if the search string/// has not been found./// </returns>size_tconstFind(stringconst&strSEARCH)const;/// <summary>/// Converts the contents of itself to a string./// </summary>/// <returns>String content</returns>stringconst&ToString()const;/// <summary>/// Appends a text to this object/// </summary>/// <param name="strVALUE">Value to be appended</param>voidAppend(stringconst&strVALUE);/// <summary>/// Sets the length of the content of this object./// </summary>/// <param name="SIZE">New reduced size</param>voidSetLength(conststring::size_typeSIZE);};}

Extensive testing of a software is crucial for qualitative code. To say that the code is tested does not give much information. The question is what is tested. Not in this case, but often it is also important to know where (in which environment) it was tested, and how - i.e. the test succession. Here is the code used to test the Maths class.