c++ cin.getline用法 C++ cin.getline及getline()用法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c++ cin.getline用法 C++ cin.getline及getline()用法详解

郭怡柔   2021-04-21 我要评论

下面先看下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++ getline()的两种用法

getline():用于读入一整行的数据。在C++中,有两种getline函数。第一种定义在头文件<istream>中,是istream类的成员函数;第二种定义在头文件<string>中,是普通函数。

第一种: 在<istream>中的getline()函数有两种重载形式:

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

作用是: 从istream中读取至多n个字符(包含结束标记符)保存在s对应的数组中。即使还没读够n个字符,如果遇到delim标识符或字数达到限制,则读取终止。delim标识符会被读取,但是不会被保存进s对应的数组中。注意,delim标识符在指定最大字符数n的时候才有效。

#include <iostream>
using namespace std;

int main()
{
 char name[256], wolds[256];
 cout<<"Input your name: ";
 cin.getline(name,256);
 cout<<name<<endl;
 cout<<"Input your wolds: ";
 cin.getline(wolds,256,',');
 cout<<wolds<<endl;
 cin.getline(wolds,256,',');
 cout<<wolds<<endl;
 return 0;
}

输入

Kevin
Hi,Kevin,morning

输出

Kevin
Hi
Kevin

第二种: 在<string>中的getline函数有四种重载形式:

istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);

用法和上第一种类似,但是读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。

is:表示一个输入流,例如cin。

str:string类型的引用,用来存储输入流中的流信息。

delim:char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到'\n',则终止输入。

#include<iostream>
#include<string>
using namespace std;
int main(){
 string str;
 getline(cin, str, 'A');
 cout<<"The string we have gotten is :"<<str<<'.'<<endl;
 getline(cin, str, 'B');
 cout<<"The string we have gotten is :"<<str<<'.'<<endl;
return 0;}

输入

i_am_A_student_from_Beijing

输出

The string we have gotten is :i_am_.
The string we have gotten is :_student_from_.

总结

以上所述是小编给大家介绍的C++ cin.getline及getline()用法详解,希望对大家有所帮助,也非常感谢大家对网站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们