求问一个小小的c++的问题,#include #include #include using namespace std;int main(){vector lines;string s = "abc\nb\n\nc\n\n\ndef";string::size_type pos1 = 0;string::size_type pos2 = 0;if(s.find('\n') = string::npos){while( (pos2 = s.find_fir

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/08 16:29:29
求问一个小小的c++的问题,#include #include #include using namespace std;int main(){vector lines;string s =

求问一个小小的c++的问题,#include #include #include using namespace std;int main(){vector lines;string s = "abc\nb\n\nc\n\n\ndef";string::size_type pos1 = 0;string::size_type pos2 = 0;if(s.find('\n') = string::npos){while( (pos2 = s.find_fir
求问一个小小的c++的问题,
#include
#include
#include
using namespace std;
int main()
{
vector lines;
string s = "abc\nb\n\nc\n\n\ndef";
string::size_type pos1 = 0;
string::size_type pos2 = 0;
if(s.find('\n') = string::npos)
{
while( (pos2 = s.find_first_of('\n',pos1)) = string::npos)
{
if(pos1 == pos2)
lines.push_back("\n");
else
{
lines.push_back(s.substr(pos1,pos2));
lines.push_back("\n");
}
++pos2;
pos1 = pos2;
}
lines.push_back(s.substr(pos1,pos2));
}
vector::iterator it;
for(it = lines.begin();it = lines.end();++it)
{
cout

求问一个小小的c++的问题,#include #include #include using namespace std;int main(){vector lines;string s = "abc\nb\n\nc\n\n\ndef";string::size_type pos1 = 0;string::size_type pos2 = 0;if(s.find('\n') = string::npos){while( (pos2 = s.find_fir
逻辑有问题.
用if(pos1 == pos2)去判断重复的\n不太可靠,还不如直接去比较\n.
另外你的输出不对,主要是s.substr(pos1,pos2)用错,第一个参数是index,第二个参数给长度.
照你的思路重写了一下,简单测试没问题,建议这类问题直接用char* 加指针,完事再转string:
#include
#include
#include
using namespace std;
int split(const string & s)
{
vector < string > lines;
string::size_type cur = 0;
string::size_type pos = 0;
while (1)
{
if (cur == s.size())
break;
if (s.at(cur) == '\n')
{
cur++;
continue;
}
if ((pos = s.find_first_of('\n',cur)) == string::npos)
{
pos = s.size();
lines.push_back(s.substr(cur,pos - cur));
break;
} else
lines.push_back(s.substr(cur,pos - cur));
cur = pos + 1;
}
string::size_type tmp = 0;
cout ::iterator it;
for (it = lines.begin(); it != lines.end(); ++it)
{
cout