C++ getline的使用

本文详细介绍了如何使用C++的getline函数从输入流读取文件内容,并将其输出到输出流的过程。通过实例演示了文件读取的基本操作,包括打开文件、读取内容以及关闭文件。此教程适用于希望了解C++文件处理基础的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


getline(istream &in, string &s)

从输入流读入一行到string s

•功能:
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. #include<fstream>  
  3. #include<string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     string buff;  
  10.     ifstream infile;  
  11.     ofstream outfile;  
  12.     cout<<"Input file name: "<<endl;  
  13.     cin>>buff;  
  14.     infile.open(buff.c_str());  
  15.   
  16.     if(!infile)  
  17.         cout<<"error"<<buff<<endl;  
  18.       
  19.     cout<<"Input outfile name: "<<endl;  
  20.     cin>>buff;  
  21.     outfile.open(buff.c_str());  
  22.       
  23.     while(getline(infile, buff))  
  24.         outfile<<buff<<endl;  
  25.   
  26.     infile.close();  
  27.     outfile.close();  
  28.     return 0;  
  29.   
  30. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值