7.C++读取文件的数据

头文件:#include <fstream>

(1) #include <fstream>#include <stdlib.h>#include <vector>using namespace std;int main(){ char buffer[256]; ifstream in("input.txt");//文件不存在会返回错误 if (! in.is_open()){ cout << "Error opening file"<<endl; exit (1); } vector<string> a; while (!in.eof()){ in.getline (buffer,100); //cout << buffer << endl; a.push_back(buffer); } for(unsigned int i=0;i<a.size();i++) cout<<a[i]<<endl; return 0;} #include <fstream>#include <stdlib.h>#include <vector>using namespace std;int main(){ char buffer[256]; ifstream in("input.txt");//文件不存在会返回错误 if (! in.is_open()){ cout << "Error opening file"<<endl; exit (1); } vector<string> a; while (!in.eof()){ in.getline (buffer,100); //cout << buffer << endl; a.push_back(buffer); } for(unsigned int i=0;i<a.size();i++) cout<<a[i]<<endl; return 0;}

#include <iostream>                                                                                                                                
#include <fstream>
#include <stdlib.h>
#include <vector>
using namespace std;
int main(){
   char buffer[256];
   ifstream in("input.txt");//文件不存在会返回错误
   if (! in.is_open()){
       cout << "Error opening file"<<endl;
       exit (1);
   }
   vector<string> a;
   while (!in.eof()){
       in.getline (buffer,100);
       //cout << buffer << endl;
       a.push_back(buffer);
    }   
   for(unsigned int i=0;i<a.size();i++)
       cout<<a[i]<<endl;
  return 0;
}

in.getline()读取出来的是字符串.

(2)或者使用如下:

ifstream in;
string getStr = "";
string tmp = "";

/*读取配置文件*/
in. open( "input.txt");
if(!in){
#if DEBUG
cout<< "打开配置文件失败(读取):" << conf_path <<endl;
#endif
return - 2;
}
while( getline(in, tmp)){ getStr += tmp;}
in. close();


注:getline读取出来的是string类型的数据.

getline不是C库函数,而是C++库函数。它会生成一个包含一串从输入流读入的字符的字符串,直到以下情况发生会导致生成的此字符串结束。1)到文件结束,2)遇到函数的定界符,3)输入达到最大限度

应用范围:

用于读取一行字符直到换行符,包括换行符,并存到string变量中;直到出现一下情况时就可以结束:

读入了文件结束标志

读到一个新行

达到字符串的最大长度

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值