C++中getline()如何使用

发布时间:2021-07-12 10:01:30 作者:Leah
来源:亿速云 阅读:212

C++中getline()如何使用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

getline()用法

getline是C++标准库函数;它有两种形式,一种是头文件< istream >中输入流成员函数;一种在头文件< string >中普通函数;

它遇到以下情况发生会导致生成的本字符串结束:(1)到文件结束,(2)遇到函数的定界符,(3)输入达到最大限度。

输入流成员函数getline()

函数语法结构:

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

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

作用是: 从istream中读取至多n个字符(包含结束标记符)保存在s对应的数组中。即使还没读够n个字符,如果遇到delim 或 字数达到限制,则读取终止,delim都不会被保存进s对应的数组中。

代码实例

#include <iostream>   using namespace std;int main(){ char name[256]; cout << "Please input your name: "; cin.getline(name, 256); cout << "The result is:  " << name << endl;  return 0;}

#include <iostream>using namespace std;int main( ){  char line[100];  cout << " Type a line terminated by 't'" << endl;  cin.getline( line, 100, 't' );  cout << line << endl;    return 0;}

普通函数getline()

函数语法结构:

在< 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);

函数的变量:

is :表示一个输入流,例如 cin。str :string类型的引用,用来存储输入流中的流信息。delim :char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到'\n',则终止输入

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

#include <iostream>#include <string>using namespace std;int main(){ string name; cout << "Please input your name: "; getline(cin, name); cout << "Welcome to here!" << name << endl;  return 0;}

#include <iostream>#include <string>using namespace std;int main(){ string name; cout << "Please input your name: "; getline(std::cin, name, '#'); cout << "Welcome to here!" << name << endl;  return 0;}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 如何使用C++中const的特性
  2. Java、Python、C++应该选择哪一个语言

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

c++ getline()

上一篇:Yii2中组件如何注册

下一篇:如何创建网关项目Spring Cloud Gateway

相关阅读

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

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