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))
    sevc.push_back(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:"
     <<filename<<endl;

     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  从流中读取字符串到s 注意 此时流中字符串是以行存储的当读到s中的时候遇到空格就结束读取(开头的空格不算),然后循环读取下空格下一个位置的字符串

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将txt文件读取vector,首先需要按照以下步骤进行操作: 1. 打开txt文件:可以使用C++fstream的ifstream类来实现。首先创建一个ifstream对象,然后使用对象的open()函数将文件路径作为参数打开txt文件。 2. 检查文件是否成功打开:在打开文件后,我们需要检查文件是否成功打开。可以使用对象的is_open()函数来判断文件是否打开成功。如果文件成功打开,则可以继续进行读取操作;否则,需要返回错误信息。 3. 读取文件内容并存储到vector:我们可以使用C++vector容器来存储读取到的txt内容。首先创建一个vector对象,然后使用一个循环来逐行读取文件内容。 4. 关闭文件:当读取文件内容后,需要关闭文件。可以使用ifstream对象的close()函数来关闭文件。 以下是一个示例代码: ```cpp #include <iostream> #include <fstream> #include <vector> #include <string> int main() { std::ifstream file; std::string line; std::vector<std::string> content; file.open("example.txt"); if (!file.is_open()) { std::cerr << "无法打开文件!" << std::endl; return 1; } while (std::getline(file, line)) { content.push_back(line); } file.close(); // 输出vector的内容 for (const auto& str : content) { std::cout << str << std::endl; } return 0; } ``` 以上代码以读取名为"example.txt"的txt文件为例,将文件内容逐行读取并存储到名为content的vector。最后通过循环输出vector的内容。根据实际情况,你可以修改文件路径和输出方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值