C++ cin.getline用法详解

  • 内容
  • 评论
  • 相关

使用 C++ 字符数组与使用 string 对象还有另一种不同的方式,就是在处理它们时必须使用不同的函数集。例如,要读取一行输入,必须使用 cin.getline 而不是 getline 函数。这两个的名字看起来很像,但它们是两个不同的函数,不可互换。

与 getline 一样,cin.getline 允许读取包含空格的字符串。它将继续读取,直到它读取至最大指定的字符数,或直到按下了回车键。以下是其用法示例:

cin.getline(sentence, 20);

getline 函数使用两个用逗号分隔的参数。第一个参数是要存储字符串的数组的名称。第二个参数是数组的大小。当 cin.getline 语句执行时,cin 读取的字符数将比该数字少一个,为 null 终止符留出空间。这样就不需要使用 setw 操作符或 width 函数。以上语句最多可读取 19 个字符,null 终止符将自动放在数组最后一个字符的后面。

下面的程序演示了 getline 函数的用法,它最多可以读取 80 个字符:

// 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.

本文标题:C++ cin.getline用法详解

本文地址:https://www.hosteonscn.com/3705.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注