如何从文件中读取字符串

zhengsyao 2003-05-23 04:15:31
请问如下的问题应该如何解决:
读取一个英文文本文件,把其中的每个单词抽取出来,作为string类型,同时把这些string放进一个vector.
本人刚接触stl,所以有很多不懂,希望多多指教啊!
...全文
218 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
aiyinsitan 2003-05-23
  • 打赏
  • 举报
回复
对不起, 上面写错了。
while( cin >> tmp )
该为
while( f >> tmp )
aiyinsitan 2003-05-23
  • 打赏
  • 举报
回复
ifstream f("filename");
string tmp;
vector<string> vec;
while( cin >> tmp )
vector.push_back( tmp );
晨星 2003-05-23
  • 打赏
  • 举报
回复
兄弟帮你做一个仅仅依靠空格来分解文件的简单示例,然后你自己完善一下吧。比如说怎么处理标点各类符号。

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

void main()
{
ifstream fin;
fin.open("C:\\a.txt");
vector<string> v_str;

string s;
while(!fin.eof())
{
fin >> s;
v_str.push_back(s);
}

vector<string>::iterator itr;
int count = 0;
for(itr = v_str.begin() ; itr < v_str.end() ; itr++)
{
cout << ++count << ": " << *itr << endl;
}
fin.close();
}
短歌如风 2003-05-23
  • 打赏
  • 举报
回复
关键在于对“单词”的定义。如果简单地作可以:
#include <fstream>
#include <vector>
#include <string>

...
std::ifstream infile(FileName);
std::vector<std::string> wordtable;
while (infile)
{
std::string aword;
infile >> aword;
if (aword != "")
wordtable.push_back(aword);
}

...
以上只是简单地把“单词”看作是“用空白符分隔的字符序列”,如果逻辑复杂一些,可再加入到wordtable中前牟aword加以处理,比如用其它分隔符再进行折分(这时aword中可能有多个单词,但决不会有一个单词分到多个aword中,除非有在行尾以-结束的单词,如果要考虑它,判断并处理就行了)、去除标点符号等。

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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