0
点赞
收藏
分享

微信扫一扫

c++中如何利用vector fstream进行文件的读取


#include<iostream>
 #include <string>
 #include <vector>
 #include <fstream>
 #include <sstream>
 using namespace std;int filetovector(string filename,vector<string>& sevc)
 {
    ifstream infile(filename.c_str());
    if(!infile)
     return 1;
    string s;
    while (getline(infile,s))
    infile.close();   //--关闭文件
  if (infile.eof()) //--遇到文件结束符
   return 4;
  if(infile.bad()) //-- 发生系统故障
   return 2;
  if(infile.fail()) //读入数据失败
   return 3;
 }
 int t_main(int argc, char *argv[])
 {
  
 vector<string> sevc;
 string filename,s;//读入文件名
 cout<<"Entet the FileName :";
 cin>>filename;//处理文件
 switch(filetovector(filename,sevc))
  {
 case 1:
     cout<<"error:can't open file:"
         return -1;
 case 2:
      cout<<"error:system failure"<<endl;
      return-1;
 case 3:
   cout<<"error:read failure"<<endl;
   return -1;
 default:
  return 1;
 }//使用istringstream从vector里每次读取一个单词的形式读取所存储的行
 istringstream isstream;for(vector<string>::iterator iter=sevc.begin();iter!=sevc.end();++iter)
 {
  isstream.str(*iter);
  while (isstream>>s)
  {
   cout<<s<<endl;
  }
  isstream.clear(); //--将istringstream流设置为有效状态
 }
 return 0;
 }

getline()是按行读取的,

isstream>>s 

举报

相关推荐

0 条评论