cin.getline(sentence, 20);
getline 函数使用两个用逗号分隔的参数。第一个参数是要存储字符串的数组的名称。第二个参数是数组的大小。当 cin.getline 语句执行时,cin 读取的字符数将比该数字少一个,为 null 终止符留出空间。这样就不需要使用 setw 操作符或 width 函数。以上语句最多可读取 19 个字符,null 终止符将自动放在数组最后一个字符的后面。
// This program demonstrates cinT s getline function
// to read a line of text into a C-string.
#include <iostream>、
using namespace std;
int main()
{
const int SIZE = 81;
char sentence[SIZE];
cout << "Enter a sentence: ";
cin.getline (sentence, SIZE);
cout << "You entered " << sentence << endl;
return 0;
}
程序输出结果:
Enter a sentence: To be, or not to be, that is the question.
You entered To be, or not to be, that is the question.
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有