使用带有C库函数的C ++字符串

时间:2012-02-04 22:30:23

标签: c++ string

当我尝试在以下行中使用atoi(con​​st char *)函数时发生错误...

externalEncryptionRawHolder[u] = atoi(parser.next()); 

'parser'对象是一个字符串解析器,'next'方法返回一个字符串。我认为错误与'atoi'函数中的字符串不是常数这一事实有关......但我不确定。错误的要点是'无法将字符串转换为const char *'。如何让我的弦不变?任何帮助都将非常感激(顺便说一句,如果你想知道索引'你'是什么,这是在'for'循环内)。

2 个答案:

答案 0 :(得分:7)

您必须致电c_str()对象上的string才能获得const char*

externalEncryptionRawHolder[u] = atoi(parser.next().c_str());

但请注意,您不应执行此操作:

const char* c = parser.next().c_str();

因为c将指向由string返回的parser.next()管理的内存,该内存在表达式的末尾被销毁,因此c点解除分配内存。第一个例子没问题,因为直到atoi返回后字符串才被销毁。

答案 1 :(得分:1)

string::c_str()会将string转换为const char*,这正是atoi所期望的。

externalEncryptionRawHolder[u] = atoi(parser.next().c_str());