A Complete Guide to Programming in C++ part 10

A Complete Guide to Programming in C++ part 10. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | OUTPUT OF CHARACTERS STRINGS AND BOOLEAN VALUES 69 Outputting Characters and Character Codes The operator interprets a number of type char as the character code and outputs the corresponding character Example char ch 0 cout ch A Outputs three characters 0 A It is also possible to output the character code for a character. In this case the character code is stored in an int variable and the variable is then output. Example int code 0 cout code Output 48 The 0 character is represented by ASCII Code 48. The program on the opposite page contains further examples. Outputting Strings You can use the operator both to output string literals such as Hello and string variables as was illustrated in previous examples. As in the case of other types strings can be positioned within output fields. Example string s spring flowers cout left Left-aligned setfill Fill character setw 20 s Field width 20 This example outputs the string spring flowers . The manipulator right can be used to right-justify the output within the field. Outputting Boolean Values By default the operator outputs boolean values as integers with the value 0 representing false and 1 true. If you need to output the strings true or false instead the flag ios boolalpha must be set. To do so use either the setf method or the manipulator boolalpha. Example bool ok true cout ok endl 1 boolalpha ok endl true You can revert this setting using the noboolalpha manipulator. 70 CHAPTER 4 INPUT AND OUTPUT WITH STREAMS FORMATTED INPUT Sample program Inputs an article label and a price include iostream Declarations of cin cout . include iomanip Manipulator setw include string using namespace std int main string label double price cout nPlease enter an article label Input the label 15 characters maximum cin setw 16 or 16 cin label Clears the buffer and resets any error flags that may be set cout nEnter the price of the article cin price Input the price Controlling output cout fixed setprecision 2 .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.