我正在尝试使用以下代码将字符串分解为整数和字符。在关于立即打印的第一部分中,我得到了正确的输出,但后来却出错了。
int Lottery::calcInvOdds(string ruleConstraint){
const char * sorted;
const char * unique;
string temp;
size_t pos;
temp = ruleConstraint;
pos = temp.find_first_of(" ");
sorted = temp.substr(0,pos).c_str();
cout << temp << endl;
cout << "S = " << sorted << endl;
temp = temp.substr(pos+1);
unique = temp.substr(0,pos).c_str();
cout << "U = " << unique << endl;
cout << "Sorted = " << sorted[0] << " " << "Unique = " << unique[0] << endl<<endl;
return 0;
}
输出是这样的:
T F
S = T
U = F
Sorted = F Unique = F
F T
S = F
U = T
Sorted = T Unique = T
但是,在使用const char *
和char sorted[2]
等数组替换temp.substr(0,pos).c_str();
并使用*temp.substr(0,pos).c_str()
后,会显示正确的输出。这种行为的原因是什么?
答案 0 :(得分:4)
sorted = temp.substr(0,pos).c_str();
这不会起作用。 temp.substr(0,pos)
返回临时string
,.c_str()
获取指向其内容的指针,语句完成后释放临时string
,使sorted
指向释放存储器中。
您最好的选择是不要费心转换为const char*
,而是将sorted
和unique
更改为string
。然后事情会像你期望的那样工作,因为字符串将一直存在,直到函数退出。
int Lottery::calcInvOdds(const string& ruleConstraint){
size_t pos = ruleConstraint.find_first_of(" ");
string sorted = ruleConstraint.substr(0, pos);
// The above line could be rewritten as:
// string sorted(ruleConstraint, 0, pos);
cout << ruleConstraint << endl;
cout << "S = " << sorted << endl;
// -- Not sure this is what you want, but it's what your code does.
#if 1
string unique = ruleConstraint.substr(pos + 1, pos);
// -- maybe you meant this
#else
size_t pos2 = ruleConstraint.find_first_of(" ", pos + 1);
string unique(ruleConstraint, pos + 1, pos2 - pos - 1);
#endif
cout << "U = " << unique << endl;
cout << "Sorted = " << sorted[0] << " " << "Unique = " << unique[0] << endl << endl;
return 0;
}