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,可用于判断文件是否结束;


猜你喜欢

转载自blog.csdn.net/u011124985/article/details/80769571