c语言getline作用,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

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

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

#include

using namespace std;

int main()

{

string name;

cout << "Please input your name: ";

getline(cin, name);

cout << "Welcome to here!" << name << endl;

return 0;

}

#include

#include

using namespace std;

int main()

{

string name;

cout << "Please input your name: ";

getline(std::cin, name, '#');

cout << "Welcome to here!" << name << endl;

return 0;

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值