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

• You can use cout with the << operator to read a variety of data types.

File output parallels this very closely:

• You must include the fstream header file.

• The fstream header file defines an ofstream class for handling output.

• You need to declare one or more ofstream 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 ofstream.

• You need to associate a specific ofstream 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 ofstream object with the << operator to output a variety of data types.

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

ofstream outFile;           // outFile an ofstream object

ofstream fout;              // fout an ofstream object

Here’s how you can associate the objects with particular files:

outFile.open("fish.txt");   // outFile used to write to the fish.txt file

char filename[50];

cin >> filename;            // user specifies a name

fout.open(filename);        // fout 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 = 125.8;

outFile << wt;         // write a number to fish.txt

char line[81] = "Objects are closer than they appear.";

fout << line << endl;   // write a line of text

The important point is that after you’ve declared an ofstream object and associated it with a file, you use it exactly as you would use cout. All the operations and methods available to cout, such as <<, endl, and setf(), are also available to ofstream objects, such as outFile and fout in the preceding examples.

In short, these are the main steps for using file output:

1. Include the fstream header file.

2. Create an ofstream object.

3. Associate the ofstream object with a file.

4. Use the ofstream object in the same manner you would use cout.

The program in Listing 6.15 demonstrates this approach. It solicits information from the user, sends output to the display, and then sends the same output to a file. You can use a text editor to examine the output file.

Listing 6.15. outfile.cpp

// outfile.cpp -- writing to a file

#include

#include                   // for file I/O

int main()

{

    using namespace std;

    char automobile[50];

    int year;

    double a_price;

    double d_price;

    ofstream outFile;               // create object for output

    outFile.open("carinfo.txt");    // associate with a file

    cout << "Enter the make and model of automobile: ";

    cin.getline(automobile, 50);

    cout << "Enter the model year: ";

    cin >> year;

    cout << "Enter the original asking price: ";

    cin >> a_price;

    d_price = 0.913 * a_price;

// display information on screen with cout

    cout << fixed;

    cout.precision(2);

    cout.setf(ios_base::showpoint);

    cout << "Make and model: " << automobile << endl;

    cout << "Year: " << year << endl;

    cout << "Was asking $" << a_price << endl;

    cout << "Now asking $" << d_price << endl;

// now do exact same things using outFile instead of cout

    outFile << fixed;

    outFile.precision(2);

    outFile.setf(ios_base::showpoint);

    outFile << "Make and model: " << automobile << endl;

    outFile << "Year: " << year << endl;

    outFile << "Was asking $" << a_price << endl;

    outFile << "Now asking $" << d_price << endl;

    outFile.close();                // done with file

    return 0;

}

Note that the final section of the program in Listing 6.15 duplicates the cout section, with cout replaced by outFile. Here is a sample run of this program:

Enter the make and model of automobile: Flitz Perky

Enter the model year: 2009

Enter the original asking price: 13500

Make and model: Flitz Perky

Year: 2009

Was asking $13500.00

Now asking $12325.50

The screen output comes from using cout. If you check the directory or folder that contains the executable program, you should find a new file called carinfo.txt. (Or it may be in some other folder, depending on how the compiler is configured.) It contains the output generated by using outFile. If you open it with a text editor, you should find the following contents:

Make and model: Flitz Perky

Year: 2009

Was asking $13500.00

Now asking $12325.50

As you can see, outFile sends precisely the same sequence of characters to the carinfo.txt file that cout sends to the display.

Program Notes

After the program in Listing 6.15 declares an ofstream object, you can use the open() method to associate the object with a particular file:

ofstream outFile;               // create object for output

outFile.open("carinfo.txt");    // associate with a file

When the program is done using a file, it should close the connection:

outFile.close();

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

Все книги серии 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.

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

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