原始Python代码:
def recv_all_until(s, crlf):
data = ""
while data[-len(crlf):] != crlf:
data += s.recv(1)
return data
我试了一下:
^{pr2}$但它显示:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
我知道问题出在while
循环中,因为一开始数据字符串是空的。那么,如何改进这一点,使其与在Python中一样工作呢?非常感谢。在
如果我们先稍微修改一下Python代码:
<>我们在C++中需要做的事情变得更加清楚: ^{pr2}$在
while
循环的第一次迭代中出现问题:因为
data
是一个空的string
,data.length()
等于0
,因此您调用data.substr(-2, 0)
。在要解决这个问题,您需要在
while
语句中添加一个行长度检查。在另外,有一种方法可以比写一个stackoverflow问题更快地找到这些错误。考虑阅读this文章。在
相关问题 更多 >
编程相关推荐