Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming

Здесь есть возможность читать онлайн «Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2003, ISBN: 2003, Издательство: Prentice Hall, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Thinking In C++. Volume 2: Practical Programming: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Thinking In C++. Volume 2: Practical Programming»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Best selling author Bruce Eckel has joined forces with Chuck Allison to write
, the sequel to the highly received and best selling
. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In
, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++.

Thinking In C++. Volume 2: Practical Programming — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Thinking In C++. Volume 2: Practical Programming», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

We also use a standard C technique for reporting program status to the calling context by returning different values from main( ). It is portable to use the statement return 0;to indicate success, but there is no portable value to indicate failure. For this reason we use the macro declared for this very purpose in : EXIT_FAILURE. As a matter of consistency, whenever we use EXIT_FAILUREwe also use EXIT_SUCCESS, even though the latter is always defined as zero .

Summary

C++ string objects provide developers with a number of great advantages over their C counterparts. For the most part, the stringclass makes referring to strings through the use of character pointers unnecessary. This eliminates an entire class of software defects that arise from the use of uninitialized and incorrectly valued pointers. C++ strings dynamically and transparently grow their internal data storage space to accommodate increases in the size of the string data. This means that when the data in a string grows beyond the limits of the memory initially allocated to it, the string object will make the memory management calls that take space from and return space to the heap. Consistent allocation schemes prevent memory leaks and have the potential to be much more efficient than "roll your own" memory management .

The stringclass member functions provide a fairly comprehensive set of tools for creating, modifying, and searching in strings. String comparisons are always case sensitive, but you can work around this by copying string data to C-style null-terminated strings and using case-insensitive string comparison functions, temporarily converting the data held in string objects to a single case, or by creating a case-insensitive string class that overrides the character traits used to create the basic_stringobject .

Exercises

1. Write a program that reverses the order of the characters in a string.

18. A palindrome is a word or group of words that read the same forward and backward. For example "madam" or "wow." Write a program that takes a string argument from the command line and prints whether the string was a palindrome or not.

19. Make your program from exercise 2 return trueeven if symmetric letters differ in case. For example, "Civic" would still return truealthough 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 replacethat 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 fromreplaced by to.

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

4: Iostreams

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 stdiolibrary .

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 stdiofacilities and explores the behavior of file and string streams in addition to the standard console streams .

Why iostreams?

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 FILEpointer 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 FileClassobject 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 .

Even though the FILEpointer is private, it isn’t particularly safe because fp( )retrieves it. Since the only effect seems to be guaranteed initialization and cleanup, why not make it public or use a structinstead? Notice that while you can get a copy of fusing fp( ), you cannot assign to f— that’s completely under the control of the class. Of course, after capturing the pointer returned by fp( ), the client programmer can still assign to the structure elements or even close it, so the safety is in guaranteeing a valid FILEpointer rather than proper contents of the structure .

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Thinking In C++. Volume 2: Practical Programming»

Представляем Вашему вниманию похожие книги на «Thinking In C++. Volume 2: Practical Programming» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Thinking In C++. Volume 2: Practical Programming»

Обсуждение, отзывы о книге «Thinking In C++. Volume 2: Practical Programming» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x