Читаем Thinking In C++. Volume 2: Practical Programming полностью

You can also define your own facets to construct customized locales.[47] Be aware that the overhead for locales is considerable. In fact, some library vendors provide different "flavors" of the standard C++ library to accommodate environments that have limited space.[48]

<p>Summary</p>

This chapter has given you a fairly thorough introduction to the iostream class library. In all likelihood, it is all you need to create programs using iostreams. However, be aware that some additional features in iostreams are not used often, but you can discover them by looking at the iostream header files and by reading your compiler’s documentation on iostreams or the references mentioned in this chapter and in the book’s preface.

<p>Exercises</p>

             1.             Open a file by creating an ifstream object. Make an ostringstream object and read the entire contents into the ostringstream using the rdbuf( ) member function. Extract a string copy of the underlying buffer and capitalize every character in the file using the Standard C toupper( ) macro defined in . Write the result out to a new file.<#TIC2V2_CHAPTER5_I190>

        24.             Create a program that opens a file (the first argument on the command line) and searches it for any one of a set of words (the remaining arguments on the command line). Read the input a line at a time, and write out the lines (with line numbers) that match to the new file.<#TIC2V2_CHAPTER5_I191>

        25.             Write a program that adds a copyright notice to the beginning of all source-code files indicated by the program’s command-line arguments.<#TIC2V2_CHAPTER5_I192>

        26.             Use your favorite text-searching program (grep, for example) to output the names (only) of all the files that contain a particular pattern. Redirect the output into a file. Write a program that uses the contents of that file to generate a batch file that invokes your editor on each of the files found by the search program.

         27.             We know that setw( ) allows for a minimum of characters read in, but what if you wanted to read a maximum? Write an effector that allows the user to specify a maximum number of characters to extract. Have your effector also work for output, in such a way that output fields are truncated, if necessary, to stay within width limits.

        28.             Demonstrate to yourself that if the fail or bad bit is set, and you subsequently turn on stream exceptions, that the stream will immediately throw an exception.

        29.             String streams accommodate easy conversions, but they come with a price. Write a program that races atoi( ) against the stringstream conversion system to see the effect of the overhead involved with stringstream.

        30.             Make a Person struct with fields such as name, age, address, etc. Make the string fields fixed-size arrays. The social security number will be the key for each record. Implement the following Database class.

class DataBase {

public:

  // Find where a record is on disk

  size_t query(size_t ssn);

  // Return the person at rn (record number)

  Person retrieve(size_t rn);

  // Record a record on disk

  void add(const Person& p);

};

Write some Person records to disk (do not keep them all in memory). When the user requests a record, read it off the disk and return it. The I/O operations in the DataBase class use read( ) and write( ) to process all Person records.

         31.             Write an operator<< inserter for the Person struct that can be used to display records in a format easily read. Practice writing it out to file.

        32.             Suppose your database for your Person structs was lost but that you have the file you wrote from the previous exercise. Recreate your database using this file. Be sure to use error checking.

        33.             Write size_t(-1) (the largest unsigned int on your platform) to a text file 1,000,000 times. Repeat, but write to a binary file. Compare the two files for size, and see how much room is saved using the binary format. (You may first want to try to calculate how much will be saved on your platform.)

        34.             Found out the maximum number of digits of precision your implementation of iostreams will print by repeatedly increasing the value of the argument to precision( ) when printing a transcendental number such as sqrt(2.0).

        35.             Write a program that reads real numbers from a file and prints their sum, average, minimum, and maximum.

        36.             Determine the output of the following program before it is executed.

//: C04:Exercise16.cpp

#include

#include

#include

#include "../require.h"

using namespace std;

#define d(a) cout << #a " ==\t" << a << endl;

void tellPointers(fstream& s) {

  d(s.tellp());

  d(s.tellg());

  cout << endl;

}

void tellPointers(stringstream& s) {

  d(s.tellp());

  d(s.tellg());

  cout << endl;

}

int main() {

  fstream in("Exercise16.cpp");

  assure(in, "Exercise16.cpp");

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

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

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

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

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

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

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

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

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