请教关于字符串流的一个小问题

zhanchili 2008-03-26 06:23:26
打开一个文件,把其中的内容按行存入一个vector中,再利用字符串流把每个单词输出到屏幕。(我写的代码只能输出来第一行)
#include<string>
#include<iostream>
#include<fstream>
#include<sstream>
#include<vector>
using namespace std;
int main()
{
cout<<"给个文件:"<<endl;
string name;
cin>>name;
ifstream instream(name.c_str());
string line;
vector<string>lines;
for(;;)
{
getline(instream,line);
lines.push_back(line);
if(instream.eof())
break;
}
instream.clear();
instream.close();
istringstream word;
for(vector<string>::const_iterator itr=lines.begin();itr!=lines.end();itr++)
{
word.str(*itr);
string aWord;
while(word>>aWord)
cout<<aWord<<'\n';
}
return 0;
}
...全文
59 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhanchili 2008-03-28
  • 打赏
  • 举报
回复
顶一下贴。
zhanchili 2008-03-27
  • 打赏
  • 举报
回复
请问word流是在哪个地方出了错呢?需要word.clear()才能继续.
hanlin1985 2008-03-26
  • 打赏
  • 举报
回复
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
cout < <"给个文件:" < <endl;
string name;
cin>>name;
ifstream instream(name.c_str());
string line;
vector <string>lines;
for(;;)
{
getline(instream,line);
lines.push_back(line);
if(instream.eof())
break;
}
instream.clear();
instream.close();
istringstream word;
for(vector <string>::const_iterator itr=lines.begin();itr!=lines.end();itr++)
{
word.str(*itr);
string aWord;
while(word>>aWord)
cout < <aWord < <'\n';
word.clear();
}
return 0;
}
HelloDan 2008-03-26
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
cout <<"给个文件:" <<endl;
string name;
cin>>name;
ifstream instream(name.c_str());
string line;
vector <string>lines;
while(getline(instream,line))
{

lines.push_back(line);

}
//instream.clear();
instream.close();

for(vector <string>::const_iterator itr=lines.begin();itr!=lines.end();itr++)
{
istringstream word(*itr);
string aWord;
while(word>>aWord)
cout <<aWord <<'\n';
}
return 0;
}

64,682

社区成员

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

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