getline的使用

函数定义:

  getline(istream &in, string &s)

作用:

  •  在C++中用 string 类型进行终端输入字符串时,解决无法输入带有空格的字符串的问题。

功能:

  从输入流中读入字符,存到string变量,直到出现以下情况为止:

  • 读入了文件结束标志'\0'
  • 读到一个新行'\n'
  • 达到字符串的最大长度

  如果getline没有读入字符,将返回false,可用于判断文本文件是否结束

注意:

  采用键盘输入需要在getline前面加入getchar吸收之前键盘输入的回车键,否则getline不进入string。

使用方式:

普通:

1 string str;
2 getline(cin,str);
3 cout<<str;

文本文件的输入:

 1 #include<iostream>
 2 #include<fstream>
 3 #include<string>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 
 9 {
10     string buff;
11     ifstream infile;
12     ofstream outfile;
13     cout<<"Input file name: "<<endl;
14     cin>>buff;
15     infile.open(buff.c_str());
16 
17      if(!infile)
18         cout<<"error"<<buff<<endl;
19 
20     cout<<"Input outfile name: "<<endl;
21     cin>>buff;
22     outfile.open(buff.c_str());
23     
24     while(getline(infile, buff))
25         outfile<<buff<<endl;
26 
27     infile.close();
28     outfile.close();
29     return 0;
30 }

 参考:

https://blog.csdn.net/slience_perseverance/article/details/19819601

https://blog.csdn.net/l211390760/article/details/81031030

转载于:https://www.cnblogs.com/Anber82/p/11351786.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值