头文件:#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)或者使用如下:
注:getline读取出来的是string类型的数据.
getline不是C库函数,而是C++库函数。它会生成一个包含一串从输入流读入的字符的字符串,直到以下情况发生会导致生成的此字符串结束。1)到文件结束,2)遇到函数的定界符,3)输入达到最大限度。
应用范围:
用于读取一行字符直到换行符,包括换行符,并存到string变量中;直到出现一下情况时就可以结束:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
如果getline没有读入字符,将返回false,可用于判断文件是否结束;