Basic Data Types and Calculations - Try It Out: Fixing the Appearance of the Output (Page 4 of 14 )
Although it may not appear so, the output from the previous example is right justified. The “ragged right” appearance is due to the fact that the output for each integer is in a field width that’s exactly the correct number of characters to accommodate the value. You can make the output look tidier by setting the field width for each data item to a value of your choice, as follows:
Although it may not appear so, the output from the previous example is right justified. The “ragged right” appearance is due to the fact that the output for each integer is in a that’s exactly the correct number of characters to accommodate the value. You can make the output look tidier by setting the field width for each data item to a value of your choice, as follows:
// Program 2.1A - Producing neat output
#include// For output to the screen
#include// For manipulators
using std::cout;
using std::endl;
using std::setw;
int main()
{
cout << setw(10) << 10 + 20 << endl; // Output is 30
cout << setw(10) << 10 - 5 << endl; // Output is 5
cout << setw(10) << 10 - 20 << endl; // Output is -10
cout << setw(10) << 10 * 20 << endl; // Output is 200
cout << setw(10) << 10/3 << endl; // Output is 3
cout << setw(10) << 10 % 3 << endl; // Output is 1
cout << setw(10) << 10 % -3 << endl; // Output is 1
cout << setw(10) << -10 % 3 << endl; // Output is -1
cout << setw(10) << -10 % -3<< endl; // Output is -1
cout << setw(10) << 10 + 20/10 - 5 << endl; // Output is 7
cout << setw(10) << (10 + 20)/(10 - 5) << endl; // Output is 6
cout << setw(10) << 10 + 20/(10 - 5) << endl; // Output is 14
cout << setw(10) << (10 + 20)/10 - 5 << endl; // Output is -2
cout << setw(10) << 4*5/3%4 + 7/3 << endl; // Output is 4
return 0; // End the program
}
Now the output looks like this:
30
5
-10
200
3
1
1
-1
-1
7
6
14
-2
4
HOW IT WORKS
That’s much nicer, isn’t it? The tidy formatting is accomplished by the changes to the output statements. Each value to be displayed is preceded in the output bysetw(10), as in the first statement:
cout << setw(10) << 10 + 20 << endl; // Output is 30
setw()is called a manipulator because it enables you to manipulate, or control, the appearance of the output. A manipulator doesn’t output anything; it just modifies the output process. Its effect is to set the field width for the next value to be output to the number of characters that you specify between the parentheses, which is 10 in this case. The field width that you set by usingsetw()only applies to the next value that is written tocout. Subsequent values will be presented in the default manner.
The additional#includestatement for the standard header <iomanip>is necessary to make thesetw()manipulator available in your program. I’ve also added ausingdeclaration so you can use thesetwname unqualified. There are other manipulators that you’ll try out in other examples as you go along. Meanwhile, you can try out this example with different field widths to see their effect.
Using VariablesCalculating with integer constants is all very well, but you were undoubtedly expecting a bit more sophistication in your C++ programs than that. To do more, you need to be able to store data items in a program, and this facility is provided by variables. A variable is an area in memory that’s identified by a name that you supply and that you can use to store an item of data of a particular type. Specifying a variable therefore requires two things: you must give it a name, and you must identify what kind of data you propose to store in it. First of all, let’s consider what options you have for defining variable names.
Calculating with integer constants is all very well, but you were undoubtedly expecting a bit more sophistication in your C++ programs than that. To do more, you need to be able to store data items in a program, and this facility is provided by variables. A is an area in memory that’s identified by a name that you supply and that you can use to store an item of data of a particular type. Specifying a variable therefore requires two things: you must give it a name, and you must identify what kind of data you propose to store in it. First of all, let’s consider what options you have for defining variable names.
Variable Names As you saw in Chapter 1, the name that you give to a variable can consist of any combination of upper- or lowercase letters, underscores, and the digits 0 to 9, but it must begin with a letter or an underscore. As I said in Chapter 1, the ANSI standard says that a variable name can also include UCS characters, and although you could use this in defining your variable names, it’s there to allow compilers to accommodate the use of national language characters that aren’t in the basic set of upper- and lowercase letters ( A to Z).
Don’t forget, you must not express any character from the basic source character set as a UCS character. All characters from the basic source character set must appear as their explicit character representation.
You saw some examples of valid variable names in Chapter 1, but here are a few more:
value monthlySalary eight_ball FIXED_VALUE JimBob
Just to remind you of what I said in Chapter 1, a variable name can’t begin with a digit, so names such as8balland7Uparen’t valid. Also, because C++ is a case-sensitive language,republicanandRepublicanare different names. You shouldn’t use variable names that begin with an underscore followed by a capital letter or that contain two successive underscores, as names of these forms are reserved for use within the standard libraries.
Generally, the names that you invent for your variables should be indicative of the kind of data that they hold. For instance, a name such asshoe_sizeis going to mean a whole lot more thanss—always assuming you’re dealing with shoe sizes, of course. You’ll find that you often want to use names that combine two or more words to make your program more understandable. One common approach for doing this uses the underscore character to link words in a single, for example:
line_count pay_rise current_debt
A convention that’s frequently adopted in C++ is to reserve names that begin with a capital letter for naming classes, which are user-defined types. You’ll learn how to define your own data types in Chapter 11. With this approach to names,Point,Person, andProgramare all immediately recognizable as user-defined types and not variables. Of course, you’re free to assign any names that you want (as long as they aren’t keywords), but if you choose names that are meaningful and name your variables in a consistent manner, it will make your programs more readable and less error-prone. Appendix B contains a list of all the C++ keywords.
Integer VariablesSuppose you want to use a variable to record how many apples you have. You can create a variable with the name apples by means of a declaration statement for the variable, as shown in Figure 2-2.
by means of a for the variable, as shown in Figure 2-2.apples by means of a for the variable, as shown in Figure 2-2.Suppose you want to use a variable to record how many apples you have. You can create a variable with the name apples by means of a for the variable, as shown in Figure 2-2.

Figure 2-2. A variable declaration
The statement in Figure 2-2 is described as a declaration because it declares the nameapples. Any statement that introduces a name into your program is a declaration for that name. The statement in the illustration is also called a definition, because it causes memory to be allocated for the variableapples. Later, you’ll meet statements that are declarations but are not definitions. A variable is created by its definition, so you can only refer to it after the definition statement. If you attempt to refer to a variable prior to its definition, you’ll get an error message from the compiler.
When you define a variable, you can also specify an initial value. For example,
int apples = 10; // Definition for the variable apples
defines the variable calledapplesand sets its initial value as10. The definition in the diagram had no initial value specified, so the memory assigned to the variable would contain whatever junk value was left over from previous use of the memory. Having junk values floating around in your program is a bad idea, and this leads to our first golden rule.
GOLDEN RULE Always initialize your variables when you define them. If you don't know what value a variable should have when you define it, initialize it to zero.
You can use variables as operands of the arithmetic operators you’ve seen in exactly the same way as you’ve used literals. The value of the variable will be the operand value. If you apply the unary minus operator to a variable, the result is a value that has the opposite sign of the value of the variable, but the same magnitude. This doesn’t change the value stored in the variable, though. You’ll see how to do that very soon.
Let’s try out some integer variables in a little program.
Next: Try It Out: Using Integer Variables >>
More Practices Articles
More By Apress Publishing
|
This article was taken from chapter two of the book Beginning ANSI C++: The Complete Language, by Ivor Horton (Apress, 2004; ISBN: 1590592271). Check it out at your favorite bookstore today. Buy this book now.
|
|