如何将文件内容读入string类型的vector容器?

tingting5278910 2011-10-04 10:20:25
如何将文件内容读入string类型的vector容器,首先打开文件,然后读入文件。这个应该怎么做?
...全文
161 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
LZS535261548 2011-10-05
  • 打赏
  • 举报
回复
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
string ifile;
cout << "Please enter file to sort: ";
cin >> ifile;
// 构造一个 ifstream 输入文件对象
ifstream infile( ifile.c_str() );
if( ! infile ) {
cerr << "error: unable to open input file: "
<< ifile << endl;
return -1;
}
string ofile = ifile + ".sort";
// 构造一个 ofstream 输出文件对象
ofstream outfile( ofile.c_str() );
if( !outfile ) {
cerr << "error: unable to open output file: "
<< ofile << endl;
return -2;
}
string buffer;
vector< string, allocator > text;
int cnt = 1;
while ( infile >> buffer ) {
text.push_back( buffer );
cout << buffer << ( cnt++ % 8 ? " " : "\n" );
}
sort( text.begin(), text.end() );
// ok: 把排序后的词打印到 outfile
vector<string, allocator>::iterator iter = text.begin();
for ( cnt = 1; iter != text.end(); ++iter, ++cnt )
outfile << *iter
<< (cnt%8 ? " " : "\n" );
return 0;
}
游戏设计师 2011-10-04
  • 打赏
  • 举报
回复
貌似实用string*会简单一点~

64,652

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧