温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

cin.getline与getline()怎么在C++中使用

发布时间:2021-03-31 17:11:26 来源:亿速云 阅读:161 作者:Leah 栏目:编程语言

本篇文章为大家展示了cin.getline与getline()怎么在C++中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

使用 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_.

上述内容就是cin.getline与getline()怎么在C++中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI