• Aucun résultat trouvé

Using files

Dans le document You Can Do It! (Page 93-96)

cout << "\n\n";

}

It might not do exactly what you want because it places uppercase letters before lowercase ones. But this should demonstrate how C++is designed for consistency of concept. There are places where that breaks down, but there are a surprising number of places where we can apply something we have learnt in one context to a different one.

Using files

I said when I outlined the problem at the beginning of this section that we would write the sorted names to a file. Perhaps others have suggested that this will be difficult; some people try to make easy things seem hard.

In order to write the names to a file we need to do several simple things. First we need to warn the compiler we will be streaming data to or from a file by including the<fstream>header. Next we need to create anofstreamobject and connect it to the file we want to write to. Then we stream the data to the

ofstreamobject (no different to streaming the data tocout).

Here is the amended earlier program with the additions in bold type face:

#include <algorithm>

#include <fstream>

#include <iostream>

#include <string>

cout << "type " << endinput << " when there are no more names. \n\n";

for(int finished(0); finished != 1; ){

cout << "type in the next name: ";

string fullname;

Three extra lines, though we might add a fourth –outfile.close();– if we want to close the file explicitly, however C++provides automatic closure of files when a program ends. (Did you notice that I included the standard header files in alphabetical order? That is a good habit which I hope you will follow.)

After you have compiled and run this program you can look at the result by openingnames.txtin Quincy (you will need to make Quincy list all the files in theChapter 4directory to see it – my thanks to Al Stevens, the author of Quincy, for modifying Quincy to make this work).

Those of you who have been thinking carefully about what I wrote earlier about making assumptions will have noticed that the above program assumes thatoutfilewill manage to open a file callednames.txt. What would happen if it fails (for example because such a file already exists but is marked by the operating system as read only)? The answer is thatoutfilewill go into a fail state. That means that attempts to use it will do nothing. In the context of this program, that is safe: the worst that can happen is that I lose my data if it fails. In other circumstances, it could be serious and I will show you how to handle that problem later.

That is enough theory for now. It is time that you did some more practical work so here are a few program exercises for you to try.

EXERCISE

1

Use your text editor to write a file of names, one per line. (Use Quincy to do this by creating a new ASCII text file – it is at the bottom of the list of new file types.) Make the last entry END and do not forget to complete that last line by pressing Return. Please do not use a word processor for this because they add all kinds of formatting information that will confuse your programs.

Now write a program that will read in that file, sort it and write the result out to another file. If you have understood how streams work in C++, this a fairly straightforward task.

[Hint available, see end of chapter]

EXERCISE

2

Write a program that will get a line of text fromstd::cinand count the number of times the letter ‘‘a’’ is used. Bonus credit if your program correctly handles ‘‘A’’ as well as ‘‘a’’.

[Hint available]

EXERCISE

3

There is a very simple free function that takes acharargument and returns the uppercase equivalent if the argument represents a lowercase letter. If thecharargument represents anything else the argument is simple returned unchanged. The declaration of this function, provided in the<cctype>header is:

char toupper(char);

If you have understood the subscripting of astd::stringobject, you should be able to write a simple program that gets a line of text from the keyboard and then displays that text with all lowercase letters converted to uppercase.

[Hint available]

EXERCISE

4

In the early days of computing when the main output device was only capable of printing letters, creative programmers used to write programs that produced pictures entirely composed of letters and punctuation marks. Produce a simple picture on the screen in the same way.

[Hint available]

EXERCISE

5

Modify the program you wrote for Exercise 4 so that the user is prompted for the name of the file with the data in it. Use astd::stringobject calledfilenameto capture

the response.

You will need to use one of my utility functions to open thestd::ifstreamobject with a file name that is stored in astd::stringvariable because the C++Standard Library does not provide such a function (that is no great problem to experienced C++

programmers, just a minor irritant).

In my headerfgw text.hthere are declarations for functions to open files for ifstreamandofstreamobjects given the filename in astd::stringvariable. The declarations are:

void open_ifstream(std::ifstream & input_file, std::string const & filename);

void open_ofstream(std::ofstream & output_file, std::string const & filename);

These declarations are innamespace fgw;so you will need to addfgw::to the function name when you use it. (Or put ausing namespace fgwdirective after you have included the header filefgw text.h.) A typical call would be:

fgw::open_ifstream(input, filename);

whereinputandfilenamehave been suitably defined. You do not need to include fgwlib.ainto the project because the definition is directly available in the header file. (I used a little trick called inline delegation which allows me to get away with putting a definition in a header file.)

Note

None of the above five exercises is as visually exciting as the things that you can do with ourplaypen

graphics facilities. However, each one requires programming skill so I hope you will take up the challenge and not elect to skip them.

Dans le document You Can Do It! (Page 93-96)