Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Demystifying C++ I/O

boolalpha and noboolalpha. If boolalpha is used, the string true will be interpreted as a Boolean value true and false will be treated as the Boolean value false. If noboolalpha is set, they will not. The default is noboolalpha.

hex, oct, and dec. Reads numbers in hexadecimal, octal, and base 10, respectively.

skipws and noskipws. Tells the stream to either skip white space when tokenizing or to read in white space as its own token.

ws. A handy manipulator that simply skips over the current series of white space at the present position in the stream.

Input and Output with Objects

As you saw earlier, you can use the << operator to output a C++ string even though it is not a basic type. In C++, objects are able to prescribe how they are output and input. This is accomplished by overloading the << operator to understand a new type or class.

Why would you want to overload <<? If you are familiar with the printf() function in C, you know that it is not flexible in this area. printf() knows about several types of data, but there really isn’t a way to give it additional knowledge. For example, consider the following simple class:

class Muffin

 

{

 

public:

 

string

getDescription() const;

void

setDescription(const string& inDescription);

int

getSize() const;

void

setSize(int inSize);

bool

getHasChocolateChips() const;

void

setHasChocolateChips(bool inChips);

protected:

 

string

mDescription;

int

mSize;

bool

mHasChocolateChips;

};

 

string Muffin::getDescription() const { return mDescription; } void Muffin::setDescription(const string& inDescription)

{

mDescription = inDescription;

}

int Muffin::getSize() const { return mSize; }

void Muffin::setSize(int inSize) { mSize = inSize; }

bool Muffin::getHasChocolateChips() const { return mHasChocolateChips; }

void Muffin::setHasChocolateChips(bool inChips) { mHasChocolateChips = inChips; }

To output an object of class Muffin using printf(), it would be nice if you could simply specify it as an argument, perhaps using %m as a placeholder:

printf(“Muffin output: %m\n”, myMuffin); // BUG! printf doesn’t understand Muffin.

389