c++ - String size undesirable output -
c++ - String size undesirable output -
i not able find bug in little piece of code. wrong it?
string f,s; f[0] = 'd'; s.append(f); cout<<f.length()<<" "<<f<<" "<<f[0]<<endl; cout<<s.length()<<" "<<s<<" "<<s[0]<<endl; output : 0 d 0 d
even if alter s.length
s.size
, result same. why s[0] = 'd'
, s.size() = 0;
?
both strings empty when create them, contain no characters. f[0]
out of bounds, , accessing element of empty container undefined behaviour, can legally happen.
you need do
string f(1, 'd'), s; // creates f 1 repetition of 'd' s.append(f); ...
or
string f, s; f += 'd'; // or f.push_back('d'), or f.append('d'), or... s.append(f); ...
c++ string
Comments
Post a Comment