Читаем C++ Primer Plus полностью

Notice that the close() method doesn’t require a filename. That’s because outFile has already been associated with a particular file. If you forget to close a file, the program will close it automatically if the program terminates normally.

Notice that outFile can use the same methods that cout does. Not only can it use the << operator, but it can use the various formatting methods, such as setf() and precision(). These methods affect only the object that invokes the method. For example, you can provide different values for different objects:

cout.precision(2);       // use a precision of 2 for the display

outFile.precision(4);    // use a precision of 4 for file output

The main point you should remember is that after you set up an ofstream object such as outFile, you use it in precisely the same matter as you use cout.

Let’s go back to the open() method:

outFile.open("carinfo.txt");

In this case, the file carinfo.txt does not exist before the program runs. In this circumstance, the open() method creates a brand new file by that name. When the file carinfo.txt exists, what happens if you run the program again? By default, open() first truncates the file; that is, it trims carinfo.txt to zero length, discarding the current contents. The contents are then replaced with the new output. Chapter 17 reveals how to override this default behavior.

Caution

When you open an existing file for output, by default it is truncated to a length of zero bytes, so the contents are lost.

It is possible that an attempt to open a file for output might fail. For example, a file having the requested name might already exist and have restricted access. Therefore, a careful programmer would check to see if the attempt succeeded. You’ll learn the technique for this in the next example.

Reading from a Text File

Next, let’s examine text file input. It’s based on console input, which has many elements. So let’s begin with a summary those elements:

• You must include the iostream header file.

• The iostream header file defines an istream class for handling input.

• The iostream header file declares an istream variable, or object, called cin.

• You must account for the std namespace; for example, you can use the using directive or the std:: prefix for elements such as cin.

• You can use cin with the >> operator to read a variety of data types.

• You can use cin with the get() method to read individual characters and with the getline() method to read a line of characters at a time.

• You can use cin with methods such as eof() and fail() to monitor the success of an input attempt.

• The object cin itself, when used as a test condition, is converted to the Boolean value true if the last read attempt succeeded and to false otherwise.

File input parallels this very closely:

• You must include the fstream header file.

• The fstream header file defines an ifstream class for handling input.

• You need to declare one or more ifstream variables, or objects, which you can name as you please, as long as you respect the usual naming conventions.

• You must account for the std namespace; for example, you can use the using directive or the std:: prefix for elements such as ifstream.

• You need to associate a specific ifstream object with a specific file; one way to do so is to use the open() method.

• When you’re finished with a file, you should use the close() method to close the file.

• You can use an ifstream object with the >> operator to read a variety of data types.

• You can use an ifstream object with the get() method to read individual characters and with the getline() method to read a line of characters at a time.

• You can use an ifstream object with methods such as eof() and fail() to monitor the success of an input attempt.

• An ifstream object itself, when used as a test condition, is converted to the Boolean value true if the last read attempt succeeded and to false otherwise.

Note that although the iostream header file provides a predefined istream object called cin, you have to declare your own ifstream object, choosing a name for it and associating it with a file. Here’s how you declare such objects:

ifstream inFile;             // inFile an ifstream object

ifstream fin;                // fin an ifstream object

Here’s how you can associate them with particular files:

inFile.open("bowling.txt");  // inFile used to read bowling.txt file

char filename[50];

cin >> filename;             // user specifies a name

fin.open(filename);          // fin used to read specified file

Note that the open() method requires a C-style string as its argument. This can be a literal string or a string stored in an array.

Here’s how you can use these objects:

double wt;

inFile >> wt;         // read a number from bowling.txt

char line[81];

fin.getline(line, 81); // read a line of text

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных