Reading Strings into char Built-In Arrays with cin

A string can be read into a built-in array of chars using stream extraction with cin. For example, the following statement reads a string into the built-in 20-element array of chars named word:

cin >> word;

The string entered by the user is stored in word. The preceding statement reads characters until a white-space character or end-of-file indicator is encountered. The string should be no longer than 19 characters to leave room for the terminating null character. The setw stream manipulator can be used to ensure that the string read into word does not exceed the size of the built-in array. For example, the statement

cin >> setw( 20 ) >> word;

specifies that cin should read a maximum of 19 characters into word and save the 20th location to store the terminating null character for the string. The setw stream manipulator is not a sticky setting—it applies only to the next value being input. If more than 19 characters are entered, the remaining characters are not saved in word, but they will be in the input stream and can be read by the next input operation.1 Of course, any input operation can also fail. We show how to detect input failures in Section 13.8.

1. To learn how to ignore extra characters in the input steam, see the article at: www.daniweb.com/software-development/cpp/threads/90228/flushing-the-input-stream.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.48.131