有关 c++ 的问题

lewis_c402 2005-05-02 01:19:01
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

string read_file_into_string()
{
ifstream ifile( "test1.txt" );
if( !ifile )
cout << "error\n";
ostringstream buf;
char ch;
while ( buf && ifile.get( ch ) )
buf.put( ch );
return buf.str();
}

int main()
{
string text = read_file_into_string();
cout << text;

vector<string::size_type> lines_of_text;
string::size_type pos = 0;

while( pos != string::npos )
{
pos = text.find( '\n', pos );
lines_of_text.push_back( pos );
} //调试时这里变成了死循环,跳不出来;高手指点

ostream_iterator<string::size_type> out( cout , " " );
copy( lines_of_text.begin(), lines_of_text.end(), out );

cin.get();
}


...全文
167 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
mostideal 2005-05-02
  • 打赏
  • 举报
回复
mark
zhousqy 2005-05-02
  • 打赏
  • 举报
回复
好快啊,来晚了。
qhfu 2005-05-02
  • 打赏
  • 举报
回复
死循环就是因为你没有从下一个位置开始找,所以这样改,如果找到尾就退出while 循环,否则从下一个位置继续找 :)
qhfu 2005-05-02
  • 打赏
  • 举报
回复
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

string read_file_into_string()
{
ifstream ifile( "test1.txt" );
if( !ifile )
cout << "error\n";
ostringstream buf;
char ch;
while ( buf && ifile.get( ch ) )
buf.put( ch );
return buf.str();
}

int main()
{
string text = read_file_into_string();
cout << text;

vector<string::size_type> lines_of_text;
string::size_type pos = 0;

while( (pos = text.find_first_of( '\n', pos ))!= string::npos )
{
lines_of_text.push_back( pos );
pos++;
} //调试时这里变成了死循环,跳不出来;高手指点

ostream_iterator<string::size_type> out( cout , " " );
copy( lines_of_text.begin(), lines_of_text.end(), out );
vector<string::size_type>::iterator it = lines_of_text.begin();
cin.get();
}
bing_huo 2005-05-02
  • 打赏
  • 举报
回复
看看这样改是不是你的意图?
bing_huo 2005-05-02
  • 打赏
  • 举报
回复
int main()
{
string text = read_file_into_string();
cout << text;

vector<string::size_type> lines_of_text;
string::size_type pos = 0;

while( pos != string::npos )
{
pos = text.find( '\n', pos+1 ); //这里要+1 否则会一直查找一个地方的

if (pos != string::npos) //这里要判断 否则会把npos插入进vector里
{
lines_of_text.push_back( pos );
}
} //调试时这里变成了死循环,跳不出来;高手指点

ostream_iterator<string::size_type> out( cout , " " );
copy( lines_of_text.begin(), lines_of_text.end(), out );

cin.get();
}
bing_huo 2005-05-02
  • 打赏
  • 举报
回复
你这个程序是什么意图??分行?? 为什么不直接用getline?

65,187

社区成员

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

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