Reputation: 61
I am trying to break a string into integer and characters using below codes. in the first section on the immediate printing I got the right output but later it is wrong.
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;
}
Output is like this:
T F
S = T
U = F
Sorted = F Unique = F
F T
S = F
U = T
Sorted = T Unique = T
But after replacing const char *
with array like char sorted[2]
and temp.substr(0,pos).c_str();
with *temp.substr(0,pos).c_str()
, Correct output was displayed. What is the reason of this behaviour?
Upvotes: 0
Views: 138
Reputation: 42825
sorted = temp.substr(0,pos).c_str();
This isn't going to work. temp.substr(0,pos)
returns a temporary string
, .c_str()
gets a pointer to its contents, and after the statement completes the temporary string
is freed, making sorted
point to freed memory.
Your best option is to not even bother converting to const char*
and instead change sorted
and unique
to be string
s. Then things will work like you expect, because the strings will persist until the function exits.
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;
}
Upvotes: 4