0

我正在尝试遍历字符串并根据初始键值和标识信息块结尾的键值复制信息块。然而,当我尝试减去我的初始值和最终值以找到我正在寻找的块的长度时,我收到了一个看似任意的值。

因此,开始和结束索引通过以下方式找到:

currentstringlocation = mystring.find("value_im_looking_to_start_at, 0);
endlocation = mystring.find("value_im_looking_to_stop_at", currentstringlocation);

然后我试图做类似的事情:

mystring.copy(newstring,(endlocation-currentlocation), currentlocation);

然而,这并没有给我想要的结果。这是我的代码及其产生的输出的摘录。

stringlocation2=topoinfo.find("\n",stringlocation+11);
topoinfo.copy(address,(stringlocation2-stringlocation+11),stringlocation+11);
cout << (stringlocation2-stringlocation+11) << "\n";
cout << stringlocation2 << "\t" << stringlocation+11 << "\n";

输出:25 59 56

很明显,我试图捕获的信息块跨越 3 个字符,但是当我减去这两个字符时,我得到 25。有人可以向我解释为什么会发生这种情况以及我该如何解决它?

4

2 回答 2

3

您计算的长度错误,请尝试以下方法:

topoinfo.copy(address, stringlocation2 - (stringlocaion + 11),
              stringlocation + 11);

在此之后,address将包含复制的字符串。但请记住:如果address是字符数组或字符指针,那么您应该自己添加终止'\0'字符!

获取子字符串的更好解决方案是实际使用该std::string::substr函数:

std::string address = topoinfo.substr(stringlocation + 11,
                                      stringlocation2 - (stringlocaion + 11));
于 2012-07-29T14:56:01.177 回答
1

应该

topoinfo.copy(address,stringlocation2-(stringlocation+11),stringlocation+11);
cout << stringlocation2-(stringlocation+11) << "\n";

你的括号错了。

于 2012-07-29T14:44:06.813 回答