2字符串-E答辩.ppt

* * 济南大学信息科学与工程学院 * C++ 程序设计 主讲人:赵亚欧 Ise_zhao@ujn.edu.cn 济南大学 信息科学与技术学院 Chapter 6 Strings 6.1 C-strings(C 风格字符串)- review C-string: a string is an array of characters (elements of type char) with the null character \0 in the last element of the array The string literal Hello actually contains 6, rather than 5,characters. char greetings[6] = {H, e, l, l, o, \0}; char greetings[ ] = Hello; char greetings[ ] = \Hello\, I said.; cout greetings; 6.1 C-strings - review If specify the size of the array and the string is shorter than this size, the remaining elements of the array are initialized with the null character \0. To include a double quote inside a string precede the quote with a back slash (\). char greetings[9] = Hello; Hello, I said. The newline (\n) escape sequence can be used in place of endl to advance to a new line. If a string is too long to fit onto a single program line, it can be broken up into smaller segments. 6.1 C-strings cout some text \n; cout some textendl; char long_string[ ] = This is the first half of the string and this is the second half.; 6.2 C-string input and output Remember that the number of elements in the char array must be one more than the number of characters in the string. Program Example P6A: a simple demonstration of C-string input and output. #include iostream using namespace std; main() { const int MAX_CHARACTERS = 10; char first_name[MAX_CHARACTERS + 1]; cout Enter your first name (maximum MAX_CHARACTERS characters) ; cin first_name; cout Hello first_name endl; } ? The extraction operator read the characters up to( but not including) the space character after John. Enter your first name (maximum 10 characters) Hello John John John Paul 6.2 C-string input and output If the user does types in more than 10 characters, what will happen? The array first_name will overflow, the excess characters will overwrite other areas of memory,

文档评论(0)

1亿VIP精品文档

相关文档