Home

Data Input/Output, Reading, and Formatting

 

Displaying Data

 

Introduction

The values and expressions used in C++ are displayed using the cout class. To make the displaying of data more realistic, the cout class is configured to handle or format data to any desired result. While the cout class is defined in the iostream file, some other files provide other extensive techniques for displaying data to the console. The C language also is equipped with other formatting functions used for the same purpose. The ability to create a program made of mixed C, C++, C++/CLI languages enhance these formatting possibilities.

General Display With cout, Write(), and WriteLine()

The ostream and the Console classes are used to display items on the console screen. The ostream class is from the ios library and commands all techniques of data output to C++ console applications. The cout we have used so far is a “child” of the ostream library. Using it, you you can display almost any type of value. For example, it can be used to display:

Instead of displaying a value just using the cout or the Console classes, you can first declare and initialize a variable before displaying its value.

Besides the cout class and the extraction operator << used to display a character, cout can be used to display a (one) character. To do this, type cout followed by a period and followed by put(). The character must be included between parentheses and single-quotes. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
	Console::Write(L"Property Type: ");
	cout.put('S');

	Console::WriteLine();
	return 0;
}

This would produce:

Property Type: S
Press any key to continue . . .

If the character is initialized from a variable, type the name of the variable between parentheses:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
	char PropertyType = 'S';
	Console::Write(L"Property Type: ");
	cout.put(PropertyType);

	Console::WriteLine();
	return 0;
}

The character can also come from a variable requested from the user.

Data Display With puts()

The C++ compiler ships with files that provide many functions that can be used to control how data displays on the screen. One of these files is the stdio.h header.

puts() is used to display a string on the console. To use it, type a double-quoted in its parentheses. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    puts("Real Estate");

    Console::WriteLine();
    return 0;
}

The puts() function lacks the formatting possibilities of cout. It is destined to only display a single string. To display more complex strings, you can combine it with other operators or functions. The string to display on a puts() function can also originate from a declared and initialized variable. In this case, you would provide the name of the variable.

Data Display With printf()

The printf() function is mostly used in the C language programs. By default, it is used to display a string on the console. To display a string using printf(), simply enclose it between double-quotes in the parentheses. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    printf("Real Estate");

    Console::WriteLine();
    return 0;
}

Data Display With printf_s()

Besides printf(), you can also use printf_s() to display a string. Simply enter it in the parentheses. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    printf_s("Real Estate");

    Console::WriteLine();
    return 0;
}

This behaves the same way as the printf().

Controlling and Formatting Data Output

 

The Width of Data Display

The cout class is equipped with width() to set the amount of space needed to display an item on the console. You can display the intended value with empty parentheses for width(). Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    double PropertyValue = 782500;

    Console::Write(L"Property Value: ");
    cout.width();
    cout << PropertyValue;

    Console::WriteLine();
    return 0;
}

This would produce:

Property Value: 782500
Press any key to continue . . .

As an alternative, you can type an integer in the parentheses of width(). In order to display the intended value that could be a string, an integer or a floating number, the compiler would count the number of characters (for a char or a string) or the number of digits (for an integer or a float, including the period for decimals). If the value of the argument you supplied is less than or equal to the number of characters or digits, the compiler would ignore the number in the parentheses and display the intended value. If the value in the parentheses is greater than the number of characters or digits, the compiler would display the intended value using the total value in the parentheses but leaving empty spaces on the left of the intended value.

The value to display comes after calling width(). If you are displaying only one value, the scenario above would apply straight forward. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    double PropertyValue = 782500;

    Console::Write(L"Property Value: ");
    cout.width(16);
    cout << PropertyValue;

    Console::WriteLine();
    return 0;
}

This would produce:

Property Value:           782500
Press any key to continue . . .

To display various values, you can call width() for each and they can use different width values as in the following example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    double PropertyValue1 = 782500,
	   PropertyValue2 = 625560,
	   PropertyValue3 = 284782;

    Console::Write(L"Property Value 1: ");
    cout.width(8);
    cout << PropertyValue1 << endl;
    Console::Write(L"Property Value 2: ");
    cout.width(14);
    cout << PropertyValue2 << endl;
    Console::Write(L"Property Value 3: ");
    cout.width(10);
    cout << PropertyValue3 << endl;

    Console::WriteLine();
    return 0;
}

This would produce:

Property Value 1:   782500
Property Value 2:         625560
Property Value 3:     284782

Press any key to continue . . .
 

Filling the Empty Space

As we have seen already, the compiler leaves empty spaces on the left side of the displaying value if the width is greater than the needed space. If you do not want that space to be empty, you can fill it with any character you want. To do that, call fill(). You can use it with empty parentheses. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    double PropertyValue1 = 782500,
		   PropertyValue2 = 625560,
		   PropertyValue3 = 284782;

    Console::Write(L"Property Value 1: ");
    cout.width(8);
    cout.fill();
    cout << PropertyValue1 << endl;
    Console::Write(L"Property Value 2: ");
    cout.width(14);
    cout << PropertyValue2 << endl;
    Console::Write(L"Property Value 3: ");
    cout.width(10);
    cout << PropertyValue3 << endl;

    Console::WriteLine();
    return 0;
}

Alternatively, you can enter in its parentheses the character that would be used in place of the empty spaces. The  character can be included between single-quotes. If no fill() was called previously, it displays the intended value "as is". If there was a previous call to fill(), the fill() immediately following would still keep the value in the parentheses of the previous fill(), then empty it. In other words, if there is another call to fill() without a value in its parentheses, no character would be displayed, until a new call to the fill(). Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    double PropertyValue1 = 782500,
	   PropertyValue2 = 625560,
	   PropertyValue3 = 284782;

    Console::Write(L"Property Value 1: ");
    cout.width(8);
    cout.fill();
    cout << PropertyValue1 << endl;
    Console::Write(L"Property Value 2: ");
    cout.width(14);
    cout.fill('#');
    cout << PropertyValue2 << endl;
    Console::Write(L"Property Value 3: ");
    cout.width(10);
    cout.fill();
    cout << PropertyValue3 << endl;

    Console::WriteLine();
    return 0;
}

This would produce:

Property Value 1:   782500
Property Value 2: ########625560
Property Value 3: ####284782

Press any key to continue . . .
 

The dec, hex, and oct Operators

The most usual way to show an integer number on the console is to display it “as is”. To display a variable that has been declared and initialized as

int Value = 152;

you would write:

cout << Value;

The compiler would take care of displaying it. If you have an integer in decimal format and would like to display its equivalent hexadecimal representation, use the hex operator as follows:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    int Value = 242;

    cout << "Value = " << Value << endl;
    cout << "Value = " << hex << Value << endl;

    Console::WriteLine();
    return 0;
}

This would produce:

Value = 242
Value = f2

Press any key to continue . . .

If you have a hexadecimal integer and would like to display it in a decimal format, simply use the cout class followed by the value. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    cout << "Number = " << 0xFE28D;

    Console::WriteLine();
    return 0;
}

This would produce:

Number = 1041037
Press any key to continue . . .

Although all integers are displayed in decimal format by default, you can explicitly ask the compiler to reinforce that notation. You can also display the same value in either format as follows:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    int Variable = 28045;

    cout << "Declared Variable: " << Variable << endl;
    cout << "In decimal: " << dec << Variable << endl;
    cout << "In hexadecimal: " << hex << Variable << endl;

    Console::WriteLine();
    return 0;
}

This would produce:

Declared Variable: 28045
In decimal: 28045
In hexadecimal: 6d8d

Press any key to continue...
 

The uppercase Attribute

As you have found out, the hex attribute is used to display the hexadecimal equivalent of a decimal number, but such a number displays in lowercase. To display the hexadecimal letters to uppercase, include the uppercase attribute. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    int Value = 242642;

    cout << "Value = " << Value << endl;
    cout << "Value = " << hex << uppercase << Value << endl;

    Console::WriteLine();
    return 0;
}

This would produce:

Value = 242642
Value = 3B3D2

Press any key to continue . . .

The uppercase attribute can precede or succeed the hex attribute.

Setting the I/O Flag

The width() is used to right-align the value(s) displayed that otherwise would be left aligned. If you want to explicitly left align a value, you can use setiosflags(). To use setiosflags(), you must qualify its flags using the library in which the flag is defined. setiosflags is defined in the iomanip.h header file of the std namespace.

The ios::left flag is used to left-align a value. Here is a simple example that displays an integer:

#include <iostream>
#include <iomanip>

using namespace std;
using namespace System;

int main()
{
    double PropertyValue = 288015;

    Console::Write(L"Property Value: ");
    cout << setiosflags(ios::left) << PropertyValue;

    Console::WriteLine();
    return 0;
}

This would produce:

Property Value: 288015
Press any key to continue . . .

After using setiosflags(), any value displayed would follow its rules. To remove the formatting set by setiosflags(), use resetiosflags(), usually with the same argument. Here is an example:

#include <iostream>
#include <iomanip>

using namespace std;
using namespace System;

int main()
{
    	double PropertyValue = 288015;
	int    YearBuilt     = 1966;

	Console::Write(L"Property Value: ");
    	cout << setiosflags(ios::left) << PropertyValue;
	Console::WriteLine();

	Console::Write(L"Year Buil:     ");
	cout << resetiosflags(ios::left) << setw(8) << YearBuilt;

	Console::WriteLine();
	return 0;
}

This would produce:

Property Value: 288015
Year Buil:         1966
Press any key to continue . . .

Formatting Floating-Point Numbers in C++

In most programs that use precise numbers, you need to be able to format your values to display appropriately. This is made possible with the use of setprecision(). This takes one value in its parentheses as the number of decimal places displayed after the period of the floating number. In order to effectively use setprecision(), first call setiosflags() with the appropriate flag. The ios::fixed flag allows you to specify the exact number of decimal values used in setprecision(). Here is an example:

#include <iostream>
#include <iomanip>

using namespace std;
using namespace System;

int main()
{
    	double PropertyValue = 265500;

	Console::Write(L"Property Value: ");
	cout << setiosflags(ios::fixed) << setprecision(2)
		 << PropertyValue << endl;

	Console::WriteLine();
	return 0;
}

This would produce:

Property Value: 265500.00

Press any key to continue . . .

Since setiosflags() and setprecision() apply their formatting to all values set after they have been called, you can use them once and format your other values. That is, until you call them again. You can also display floating numbers using a scientific format. To do that, set the flag of setiosflags() to ios::scientific. Here is an example:

#include <iostream>
#include <iomanip>

using namespace std;
using namespace System;

int main()
{
    double Pop = 25.44059,
           Distance = 212.625,
           MaxExp = 709.78222656;

	Console::Write(L"Population: ");
	cout << setiosflags(ios::scientific) << setprecision(2);
 	cout << Pop << endl;
	Console::Write("Distance: ");
	cout << Distance << endl;
	Console::Write("Exponent: ");
	cout << MaxExp << endl;

	Console::WriteLine();
	return 0;
}

This would produce:

Population: 2.54e+001
Distance: 2.13e+002
Exponent: 7.10e+002

Press any key to continue . . .

C How to Display Data

The C language is the parent of C++. As such, C++ inherits what is available from C. This flexibility also allows you to mix the way things are done in C and the features that are available in C++. Although C is C++’ parent, you don't need to know (anything) about C in order to program in C++. Nevertheless, we will review these features transparently and we will be concerned only with the reason we are here: how to program in C++.

To format the display of data in C++, the cout class is complete. In some circumstances, you will need to know how other objects format data. The most common way to display data in C, and some legacy C++ code, is with printf(). As flexible as it is, it doesn't use the type of syntax we use in C++.

To display data, everything depends on how you want it to appear. Data types are divided in categories: characters, integers, floating-point numbers, and strings. To display a particular type, you type the percent operator “%”, followed by the category of data. An example would be “%d”. To display a character, use the %c format to represent a character variable. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    char PropertyType = 'S';

    printf("Property Type: %c", PropertyType);

    Console::WriteLine();
    return 0;
}

To display an integer, use the %operator with one of the following tags:

Tag Integer Type to Display
d signed decimal integer
i signed decimal integer
o unsigned octal integer
u unsigned decimal integer
x unsigned hexadecimal int (with a, b, c, d, e, f)
X unsigned hexadecimal int (with A, B, C, D, E, F)

To display a floating-point number, use the % operator with one of the following formats:

 

Tag To display
f signed value of the form [-]dddd.dddd
e signed value of the form [-]d.dddd or e[+/-]ddd
g signed value in either e or f form, based on given value and precision.
Trailing zeros and the decimal point are printed if necessary.
E Same as e; with E for exponent
G Same as g; with E for exponent if e format used

To set the number of decimal places after the period, type the % operator, followed by a period, followed by an integer for the number of decimal places desired, followed by the desired tag. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

int main()
{
    double Floater = 3255.01265;

    printf("Floater: %.3f", Floater);
    
    return 0;
}

To display a string, use the %s format.

Data Input

 

Using cin

Data input in C++ is performed using the cin class. The cin class is configured with so much flexibility (in C++, we consider that it is overloaded; in reality, it is the >> operator that is overloaded) that it can retrieve any type of declared regular variable. This includes integers, characters, floating-point numbers, or arrays of characters. Here are examples of variables that the cin class can handle:

#include <iostram>

using namespace std;
using namespace System;

int main()
{
    Console::WriteLine("Enter a natural number: ";
    int Natural;
    // Retrieve an integer
    cin >> Natural;

    Console::WriteLine("Type a decimal number: ";
    float Floater;
    // Requesting a floating pointing number
    cin >> Floater;

    Console::WriteLine("Type another decimal number: ";
    double Precision;
    // Retrieving a double-precision number
    cin >> Precision;

    Console::WriteLine("Are you ready for C++ (y=Yes/n=No)? ";
    char Answer;
    // Requesting a character
    cin >> Answer;

    Console::WriteLine("\nHere is what we got from you");
    Console::Write("Natural Number: ");
    Console::WriteLine(Natural);
    Console::WriteLine("Floating Number: ");
    Console::WriteLine(Floater);
    Console::WriteLine("Double Precision: ");
    Console::WriteLine(Precision);
    
    return 0;
}
 

C How to Input Data

To request data from the user, or to retrieve it somehow, you can use scanf_s() that is part of the stdio.h file. To use it, you must provide two pieces of information. First enter the type of variable in the parentheses. Each data type is represented by a letter as follows:

 

Character Used for
c A single character
d An integer
e A floating-point number
f A floating-point number
g A floating-point number
h A short integer
i A decimal, a hexadecimal, or an octal integer
o An octal integer
s A string followed by a white space character
u An unsigned decimal integer
x A hexadecimal integer

When calling scanf_s() to retrieve a specific value, the appropriate character must be preceded by an ampersand “%” and both must be included in double-quotes. For example, to request an integer, you would write “%d”. The second piece of information is the name of the declared variable. To use scanf_s(), you can include it in a C program.

Accessories

 

Exiting a Program

Many of the applications we have written so far stopped when the compiler found the return 0; line at the end of main(). In some circumstances it will be necessary to stop a program from a particular section if a bad or unexpected situation occurs. This is handled by using exit(). When called from anywhere, exit() closes everything from the program and stops it. The value you enter in the parentheses as an integer determines how successful the termination occurred. If you enter 0, the program terminated successfully. Any other value indicates that there was an error during the termination. Here is an example:

#include <iostream>
#include <iomanip>

using namespace std;
using namespace System;

int main()
{
    double Pop = 25.44059,
           Distance = 212.625,
           MaxExp = 709.78222656;

	Console::Write(L"Population: ");
	cout << setiosflags(ios::scientific) << setprecision(2);
 	cout << Pop << endl;

	exit(0);

	Console::Write("Distance: ");
	cout << Distance << endl;
	Console::Write("Exponent: ");
	cout << MaxExp << endl;

	Console::WriteLine();
	return 0;
}

This would produce:

Population: 2.54e+001
Press any key to continue . . .

Notice that the program doesn't get to the end; it stops where exit(0) is positioned. Besides exit(), you can use _exit() to stop the program. As opposed to exit() that closes everything from the program and exits, the _exit() function stops the program without closing the other parts. The value in the parentheses determines how the program terminates. If it is 0, the program would terminate successfully. Any other value indicates an error.

Aborting a Program

Sometimes a program terminates with a message box sent by the operating system. An example would be when a user is asked to provide a floating-point number but types a string and the program is supposed to multiply the provided value by another number. The program would stop or hang and display a message of abnormal termination. You can also create your own abnormal termination using abort(). When called, abort() terminates the program and sends an error message to the operating system. The OS uses different codes to identify these types of errors. Upon exiting, abort() terminates with an error code of 3. When the operating system receives it, it displays a message box.

You can click one of the buttons. If you click Ignore, the operating system can let you know that there was an abnormal termination.

Terminating a Program

If something bad happens in your program, the program is prepared to stop it. We will learn about some of these unusual but possible situations when studying exception handling. Nevertheless, if you suspect such a thing and would like to stop the program, you can use exit(), _exit(), or abort() we have just seen. Alternatively, you can stop a program using terminate(). You can call terminate() the same way we did with the exit() or abort().

Clearing the Screen

When an application is running (that is, a console application), for example while a user is performing data entry, the program processes one statement at a time in a top-down approach. When the user finishes, you will usually display the result on the screen. If the program is long, at one time it would fill out the screen and this could make the displayed result confusing with the data processing. One way you can approach this is to erase everything on the the screen. To do this, you can use system() and type "cls" in its parentheses.

system() is defined in the iostream.h header file of the std namespace. Here is an example:

#include <iostream>

using namespace std;
using namespace System;

public value class CHouse
{
public:
	__wchar_t TypeOfHome;
	int NumberOfBedrooms;
	double NumberOfBathrooms;
	Byte Stories;
	int YearBuilt;
	double Value;
};

int main()
{
	CHouse ^ Townhouse = gcnew CHouse;

	Townhouse->YearBuilt = 1986;
	Townhouse->NumberOfBathrooms = 1.5;
	Townhouse->Stories = 3;
	Townhouse->Value = 348255;
	Townhouse->NumberOfBedrooms = 3;
	Townhouse->TypeOfHome = L'T';

	Console::WriteLine(L"Real Estate - Townhouse");
	Console::Write("Type of Home:        ");
	Console::WriteLine(Townhouse->TypeOfHome);
	Console::Write("Number of Bedrooms:  ");
	Console::WriteLine(Townhouse->NumberOfBedrooms);
	Console::Write("Number of Bathrooms: ");
	Console::WriteLine(Townhouse->NumberOfBathrooms);
	Console::Write("Number of Stories:   ");
	Console::WriteLine(Townhouse->Stories);
	Console::Write("Year Built:          ");
	Console::WriteLine(Townhouse->YearBuilt);
	Console::Write("Monetary Value:      ");
	Console::WriteLine(Townhouse->Value);

	Console::Write(L"Press Enter to view the next property . . .");
	Console::ReadLine();

	system("cls");

	CHouse ^ SingleFamily = gcnew CHouse;

	SingleFamily->YearBuilt = 2000;
	SingleFamily->NumberOfBathrooms = 3.5;
	SingleFamily->Stories = 3;
	SingleFamily->Value = 675855;
	SingleFamily->NumberOfBedrooms = 5;
	SingleFamily->TypeOfHome = L'S';
	
	Console::WriteLine(L"Real Estate - Single Family");
	Console::Write("Type of Home:        ");
	Console::WriteLine(SingleFamily->TypeOfHome);
	Console::Write("Number of Bedrooms:  ");
	Console::WriteLine(SingleFamily->NumberOfBedrooms);
	Console::Write("Number of Bathrooms: ");
	Console::WriteLine(SingleFamily->NumberOfBathrooms);
	Console::Write("Number of Stories:   ");
	Console::WriteLine(SingleFamily->Stories);
	Console::Write("Year Built:          ");
	Console::WriteLine(SingleFamily->YearBuilt);
	Console::Write("Monetary Value:      ");
	Console::WriteLine(SingleFamily->Value);

	Console::WriteLine();
	return 0;
}

Here is an example of running the program:

Screen 1:

Real Estate - Townhouse
Type of Home:        T
Number of Bedrooms:  3
Number of Bathrooms: 1.5
Number of Stories:   3
Year Built:          1986
Monetary Value:      348255
Press Enter to view the next property . . .

Screen 2:

Real Estate - Single Family
Type of Home:        S
Number of Bedrooms:  5
Number of Bathrooms: 3.5
Number of Stories:   3
Year Built:          2000
Monetary Value:      675855

Press any key to continue . . .

C++/CLI Data Reading

 

Introduction

So far, we have used the Console class' Write() and WriteLine() to display things on the screen. While Write() is used to display something on the screen, you can use Read() to get a value from the user. To use it, the name of a variable can be assigned to it. The formula used is:

VariableName = Console::Read();

This simply means that, when the user types something and presses Enter, what the user had typed would be given (the word is assigned) to the variable specified on the left side of the assignment operator.

Read() doesn't always have to assign its value to a variable. For example, it can be used on its own line, which simply means that the user is expected to type something but the value typed by the user would not be used for any significant purpose.

Besides Read(), you can use ReadLine(). Like WriteLine(), after performing its assignment, ReadLine() sends the caret to the next line. Otherwise, it plays the same role as Read().

Practical LearningPractical Learning: Introducing Data Reading

  1. To start a new program, launch Microsoft Visual C++ 2005
  2. On the main menu, click File -> New -> Project...
  3. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  4. In the Name box, replace the string with RealEstate6 and click OK
  5. On the main menu, click Project -> Add New Item...
  6. To create a header file, in the Templates list, click Header File (.h)
  7. Set the Name to Property and click Add
  8. Complete the file as follows:
     
    #pragma once
    using namespace System;
    
    namespace RealEstate
    {
        public ref class CProperty
        {
        public:
            long PropertyNumber;
            String ^ Address;
            String ^ City;
            String ^ State;
            String ^ ZIPCode;
            int Bedrooms;
            float Bathrooms;
            int YearBuilt;
            double MarketValue;
        };
    }
  9. To create another header file, on the main menu, click Project -> Add New Item...
  10. In the Templates list, make sure Header File (.h) is selected.
    Set the Name to House and press Enter
  11. Complete the file as follows:
     
    #pragma once
    
    #include "Property.h"
    
    using namespace System;
    
    namespace RealEstate
    {
        public ref class CHouse : public CProperty
        {
        public:
            Byte Stories;
            int  Condition;
            unsigned NumberOfGarageSpaces;
        };
    }
  12. To create one more header file, on the main menu, click Project -> Add New Item...
  13. In the Templates list, make sure Header File (.h) is selected.
    Set the Name to SingleFamily and click Add
  14. Complete the file as follows:
     
    #pragma once
    #include "House.h"
    
    using namespace System;
    
    namespace RealEstate
    {
        public ref class CSingleFamily : public CHouse
        {
        public:
            __wchar_t Style;
            double LotSizeInSqFt;
        };
    }
  15. To create a source file, on the main menu, click Project -> Add New Item...
  16. In the Templates list, click C++ File (.cpp)
  17. In the New box, type Exercise and click Add
  18. In the empty file, type:
     
    #include "SingleFamily.h"
    using namespace RealEstate;
    
    int main()
    {
        CSingleFamily ^ home = gcnew CSingleFamily;    
    
        Console::WriteLine();
        return 0;
    }
  19. To execute the application, on the main menu, click Debug -> Start Without Debugging
  20. Click Yes 
  21. Close the DOS window

String Value Request

In most assignments of your programs, you will not know the value of a string when writing your application. For example, you may want the user to provide such a string. To request a string (or any of the variables we will see in this lesson), you can call Read() or ReadLine() and assign it to the name of the variable whose value you want to retrieve. Here is an example:

using namespace System;

int main()
{
    String ^ FirstName;

    Console::Write(L"Enter First Name: ");
    FirstName = Console::ReadLine();

    Console::WriteLine();

    return 0;
}

Character and Number Request

Everything the user types is a string and the compiler may not analyze it without your asking it to do so. Therefore, if you want to get a number from the user, first request a string. Here is an example:

using namespace System;

int main()
{
    int Number;
    String ^ strNumber;

    strNumber = Console::ReadLine();

    Console::WriteLine();

    return 0;
}

After getting the string, you must convert it to a number. To perform this conversion, each data type of the .NET Framework provides a mechanism called Parse. To use Parse, type the data type, followed by the :: operator, followed by Parse, and followed by parentheses. In the parentheses of Parse, type the string that you got from the user. Here is an example:

using namespace System;

int main()
{
    int Number;
    String ^strNumber;

    strNumber = Console::ReadLine();
    Number = int::Parse(strNumber);

    Console::WriteLine();

    return 0;
}

An advanced (more complicated) but faster way to do this is to type Console::ReadLine() in the parentheses of Parse(). This has the same effect. Here is an example:

using namespace System;

int main()
{
    int Number;
	
    Number = int::Parse(Console::ReadLine());

    return 0;
}

Practical LearningPractical Learning: Requesting Data

  1. To request different values from the user, change the contents of the Exercise.cpp file as follows:
     
    #include <iostream>
    #include "SingleFamily.h"
    
    using namespace std;
    using namespace RealEstate;
    
    int main()
    {
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
        CSingleFamily ^ home = gcnew CSingleFamily;    
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("To create a listing, enter the following information");
        Console::Write("Property #:    ");
        home->PropertyNumber = long::Parse(Console::ReadLine());
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        home->Condition = int::Parse(Console::ReadLine());
        Console::Write("Street Address: ");
        home->Address = Console::ReadLine();
        Console::Write("City:           ");
        home->City = Console::ReadLine();
        Console::Write("State:          ");
        home->State = Console::ReadLine();
        Console::Write("ZIP Code:       ");
        home->ZIPCode = Console::ReadLine();
        Console::Write("Bedrooms:       ");
        home->Bedrooms = int::Parse(Console::ReadLine());
        Console::Write("Bathrooms:      ");
        home->Bathrooms = float::Parse(Console::ReadLine());
        Console::Write("Stories:        ");
        home->Stories = int::Parse(Console::ReadLine());
        Console::Write("Year Built: ");
        home->YearBuilt = int::Parse(Console::ReadLine());
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        home->Style = __wchar_t::Parse(Console::ReadLine());
        Console::Write("Garage Spaces:  ");
        home->NumberOfGarageSpaces = int::Parse(Console::ReadLine());
        Console::Write("Total Lot Size: ");
        home->LotSizeInSqFt = double::Parse(Console::ReadLine());
        Console::Write("Market Value:   ");
        home->MarketValue = double::Parse(Console::ReadLine());
      
        system("cls");
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("=//= Property Listing =//=");
        Console::Write("Property #:   ");
        Console::WriteLine(home->PropertyNumber);
        Console::Write("Address:      ");
        Console::WriteLine(home->Address);
        Console::Write("              ");
        Console::Write(home->City);
        Console::Write(", ");
        Console::Write(home->State);
        Console::Write(" ");
        Console::WriteLine(home->ZIPCode);
        Console::Write("Condition:    ");
        Console::WriteLine(home->Condition);
        Console::Write("Style:        ");
        Console::WriteLine(home->Style);
        Console::Write("Bedrooms:     ");
        Console::WriteLine(home->Bedrooms);
        Console::Write("Bathrooms:    ");
        Console::WriteLine(home->Bathrooms);
        Console::Write("Stories:      ");
        Console::WriteLine(home->Stories);
        Console::Write("Year Built:   ");
        Console::WriteLine(home->YearBuilt);
        Console::Write("Garage Spaces:  ");
        Console::WriteLine(home->NumberOfGarageSpaces);
        Console::Write("Lot Size:     ");
        Console::WriteLine(home->LotSizeInSqFt);
        Console::Write("Market Value: ");
        Console::WriteLine(home->MarketValue);
    
        Console::WriteLine();
        return 0;
    }
  2. Execute the application to test it. Here is an example:
     
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    =//= Property Listing =//=
    Property #:   802400
    Address:      8244 Ramses Avenue
                  College Park, MD 20707
    Condition:    1
    Style:        C
    Bedrooms:     4
    Bathrooms:    3.5
    Stories:      3
    Year Built:   1988
    Garage Spaces:  2
    Lot Size:     7144.64
    Market Value: 650845
    
    Press any key to continue . . .
  3. Close the DOS window

Formatting Data Display

 

Introduction

Instead of using two Write() or a combination of Write() and WriteLine() to display data, you can convert a value to a string and display it. To do this, you can provide two strings to Write() or WriteLine() and separate them with a comma:

  1. The first part of the string provided to Write() or WriteLine() is the complete string that will display to the user. This first string itself can be made of different sections:
    1. One section is a string in any way you want it to display
    2. Another section is a number included between an opening curly bracket "{" and a closing curly bracket "}". This combination of "{" and "}" is referred to as a placeholder

      You can put the placeholder anywhere inside of the string. The first placeholder must have number 0. The second must have number 1, etc. With this technique, you can create the string anyway you like and use the placeholders anywhere inside of the string
  2. The second part of the string provided to Write() or WriteLine() is the value that you want to display. It can be one value if you used only one placeholder with 0 in the first string. If you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

using namespace System;

int main()
{
    String ^ FullName = L"Anselme Bogos";
    int Age = 15;
    double HSalary = 22.74;

    Console::WriteLine(L"Full Name: {0}", FullName);
    Console::WriteLine(L"Age: {0}", Age);
    Console::WriteLine(L"Distance: {0}", HSalary);

    return 0;
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Distance: 22.74

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

Write("To Display {0} {1} {2}", First, Second, Third);

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

Conversion To String

We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, each .NET Framework data type provides a mechanism called ToString.

To conversion a value of a primitive data type to a string, type the name of the variable, followed by a period, followed by ToString(). Here is an example:

using namespace System;

int main()
{
    String ^ FullName = L"Anselme Bogos";
    int Age = 15;
    double HSalary = 22.74;

    Console::WriteLine(L"Full Name: {0}", FullName);
    Console::WriteLine(L"Age: {0}", Age.ToString());
    Console::WriteLine(L"Distance: {0}", HSalary.ToString());

    return 0;
}

In some cases, you will type something in the parentheses of ToString().

Number Formatting

To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to display it to the user. You can display a natural number in a common value or, depending on the circumstance, you may prefer to show it as a hexadecimal value. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of the decimal separator and in some cases, you may want to display a salary with only 2 decimal places.

The System namespace provides a specific letter that you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letters from the following table. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are:

  Character Used For
  c C Currency values
  d D Decimal numbers
  e E Scientific numeric display such as 1.45e5
  f F Fixed decimal numbers
  g G General and most common type of numbers
  n N Natural numbers
  r R Roundtrip formatting
  x X Hexadecimal formatting
  p P Percentages

Here are examples:

using namespace System;

int main()
{
    double Distance = 248.38782;
    int Age = 15;
    int NewColor = 3478;
    double HSalary = 22.74, HoursWorked = 35.5018473;
    double WeeklySalary = HSalary * HoursWorked;

    Console::WriteLine(L"Distance: {0}", Distance.ToString(L"E"));
    Console::WriteLine(L"Age: {0}", Age.ToString());
    Console::WriteLine(L"Color: {0}", NewColor.ToString(L"X"));
    Console::WriteLine(L"Weekly Salary: {0} for {1} hours",
                 WeeklySalary.ToString(L"c"), HoursWorked.ToString(L"F"));

    return 0;
}

This would produce:

Distance: 2.483878E+002
Age: 15
Color: D96
Weekly Salary: $807.31 for 35.50 hours

As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value.

As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon operator followed by the letter.

Line Formatting

In the above programs, to display a line of text, we used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can format how a string or a line of text should display. There are mechanisms to control the amount of space used to display a string of text and how to align that string on its line.

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placeholder and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

using namespace System;

int main()
{
    double Distance = 248.38782;
    int Age = 15;
    int NewColor = 3478;
    double HSalary = 22.74, HoursWorked = 35.5018473;
    double WeeklySalary = HSalary * HoursWorked;

    Console::WriteLine(L"Distance: {0:20}", Distance.ToString(L"E"));
    Console::WriteLine(L"Age: {0,14}", Age.ToString());
    Console::WriteLine(L"Color: {0}", NewColor.ToString(L"X"));
    Console::WriteLine(L"Weekly Salary: {0:C,8}", WeeklySalary.ToString(L"c"));
 
    return 0;
}

This would produce:

Distance: 2.483878E+002
Age:             15
Color: D96
Weekly Salary: $807.31
Press any key to continue . . .

The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.

Practical LearningPractical Learning: Formatting Data

  1. To format the values displayed by the application, change the contents of the Exercise.cpp file as follows:
     
    #include <iostream>
    #include "SingleFamily.h"
    
    using namespace std;
    using namespace RealEstate;
    
    int main()
    {
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
        CSingleFamily ^ home = gcnew CSingleFamily;    
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("To create a listing, enter the following information");
        Console::Write("Property #:    ");
        home->PropertyNumber = long::Parse(Console::ReadLine());
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        home->Condition = int::Parse(Console::ReadLine());
        Console::Write("Street Address: ");
        home->Address = Console::ReadLine();
        Console::Write("City:           ");
        home->City = Console::ReadLine();
        Console::Write("State:          ");
        home->State = Console::ReadLine();
        Console::Write("ZIP Code:       ");
        home->ZIPCode = Console::ReadLine();
        Console::Write("Bedrooms:       ");
        home->Bedrooms = int::Parse(Console::ReadLine());
        Console::Write("Bathrooms:      ");
        home->Bathrooms = float::Parse(Console::ReadLine());
        Console::Write("Stories:        ");
        home->Stories = int::Parse(Console::ReadLine());
        Console::Write("Year Built:     ");
        home->YearBuilt = int::Parse(Console::ReadLine());
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        home->Style = __wchar_t::Parse(Console::ReadLine());
        Console::Write("Garage Spaces:  ");
        home->NumberOfGarageSpaces = int::Parse(Console::ReadLine());
        Console::Write("Total Lot Size: ");
        home->LotSizeInSqFt = double::Parse(Console::ReadLine());
        Console::Write("Market Value:   ");
        home->MarketValue = double::Parse(Console::ReadLine());
      
        system("cls");
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("=//= Property Listing =//=");
        Console::WriteLine("Property #:    {0}", home->PropertyNumber);
        Console::WriteLine("Address:       {0}\n              {1}, {2} {3}",
    	                home->Address, home->City,
    			home->State, home->ZIPCode);
        Console::WriteLine("Condition:     {0}", home->Condition);
        Console::WriteLine("Style:         {0}", home->Style);
        Console::WriteLine("Bedrooms:      {0}", home->Bedrooms);
        Console::WriteLine("Bathrooms:     {0}", home->Bathrooms);
        Console::WriteLine("Stories:       {0}", home->Stories);
        Console::WriteLine("Year Built:    {0}", home->YearBuilt);
        Console::WriteLine("Garage Spaces: {0} SqFt", home->NumberOfGarageSpaces);
        Console::WriteLine("Lot Size:      {0:F}", home->LotSizeInSqFt);
        Console::WriteLine("Market Value:  {0:C}", home->MarketValue);
    
        Console::WriteLine();
        return 0;
    }
  2. Execute the application to test it. Here is an example:

  3.  
    Screen 1
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    To create a listing, enter the following information
    Property #:    258904
    Property Condition
    0. Unknown
    1. Excellent
    2. Good (may need minor repair
    3. Acceptable (needs major repair)
    4. Even (land is more important)
    Your Choice:    2
    Street Address: 824 Green Castle Rd
    City:           Silver Spring
    State:          MD
    ZIP Code:       20906
    Bedrooms:       5
    Bathrooms:      2.5
    Stories:        3
    Year Built: 1972
    Style
    U. Unknown
    S. Split Level
    C. Colonial
    G. Georgial
    Your Choice:    G
    Garage Spaces:  0
    Total Lot Size: 5688.82
    Market Value:   645840
    Screen 2
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    =//= Property Listing =//=
    Property #:    258904
    Address:       824 Green Castle Rd
                   Silver Spring, MD 20906
    Condition:     2
    Style:         G
    Bedrooms:      5
    Bathrooms:     2.5
    Stories:       3
    Year Built:    1972
    Garage Spaces: 0
    Lot Size:      5688.82
    Market Value:  $645,840.00
    
    Press any key to continue . . .
  4. Close the DOS window

Previous Copyright © 2006-2016, FunctionX, Inc. Next