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

         19.             Make your program from exercise 2 return true even if symmetric letters differ in case. For example, "Civic" would still return true although the first letter is capitalized.

        20.             Make your program from exercise 3 report true even if the string contains punctuation and spaces. For example "Able was I, ere I saw Elba." would report true.

         21.             Using the following strings and only chars (no string literals or magic numbers):

string one("I walked down the canyon with the moving mountain bikers.");

string two("The bikers passed by me too close for comfort."); string three("I went hiking instead.")

         produce the following sentence:

"I moved down the canyon with the mountain bikers. The mountain bikers passed by me too close for comfort. So I went hiking instead."

        22.             Write a program named replace that takes three command-line arguments representing an input text file, a string to replace (call it from), and a replacement string (call it to). The program should write a new file to standard output with all occurrences of from replaced by to.

        23.             Repeat the previous exercise but replace all instances of from regardless of case.

<p>4: Iostreams</p>

You can do much more with the general I/O problem than just take standard I/O and turn it into a class.

Wouldn’t it be nice if you could make all the usual "receptacles"—standard I/O, files, and even blocks of memory—look the same so that you need to remember only one interface? That’s the idea behind iostreams. They’re much easier, safer, and sometimes even more efficient than the assorted functions from the Standard C stdio library.

The iostreams classes are usually the first part of the C++ library that new C++ programmers learn to use. This chapter discusses how iostreams are an improvement over C’s stdio facilities and explores the behavior of file and string streams in addition to the standard console streams.

<p>Why iostreams?</p>

You might wonder what’s wrong with the good old C library. Why not "wrap" the C library in a class and be done with it? Indeed, this is the perfect thing to do in some situations. For example, suppose you want to make sure the file represented by a stdio FILE pointer is always safely opened and properly closed, without having to rely on the user to remember to call the close( ) function. The following program is such an attempt.

//: C04:FileClass.h

// stdio files wrapped

#ifndef FILECLASS_H

#define FILECLASS_H

#include

#include

class FileClass {

  std::FILE* f;

public:

  struct FileClassError : std::runtime_error {

  public:

    FileClassError(const char* msg)

      : std::runtime_error(msg) {}

  };

  FileClass(const char* fname, const char* mode = "r");

  ~FileClass();

  std::FILE* fp();

};

#endif // FILECLASS_H ///:~

When you perform file I/O in C, you work with a naked pointer to a FILE struct, but this class wraps around the pointer and guarantees it is properly initialized and cleaned up using the constructor and destructor. The second constructor argument is the file mode, which defaults to "r" for "read.".

To fetch the value of the pointer to use in the file I/O functions, you use the fp( ) access function. Here are the member function definitions:.

//: C04:FileClass.cpp {O}

// FileClassImplementation

#include "FileClass.h"

#include

#include

using namespace std;

FileClass::FileClass(const char* fname, const char* mode) {

  if((f = fopen(fname, mode)) == 0)

    throw FileClassError("Error opening file");

}

FileClass::~FileClass() { fclose(f); }

FILE* FileClass::fp() { return f; } ///:~

The constructor calls fopen( ), as you would normally do, but it also ensures that the result isn’t zero, which indicates a failure upon opening the file. If the file does not open as expected, an exception is thrown.

The destructor closes the file, and the access function fp( ) returns f. Here’s a simple example using class FileClass:.

//: C04:FileClassTest.cpp

// Tests FileClass

//{L} FileClass

#include

#include

#include "FileClass.h"

using namespace std;

int main() {

  try {

    FileClass f("FileClassTest.cpp");

    const int BSIZE = 100;

    char buf[BSIZE];

    while(fgets(buf, BSIZE, f.fp()))

      fputs(buf, stdout);

  }

  catch(FileClass::FileClassError& e) {

    cout << e.what() << endl;

    return EXIT_FAILURE;

  }

  return EXIT_SUCCESS;

} // File automatically closed by destructor

///:~

You create the FileClass object and use it in normal C file I/O function calls by calling fp( ). When you’re done with it, just forget about it; the file is closed by the destructor at the end of its scope.

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

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

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

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

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

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

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

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

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