+ 1

why my code is giving size more than my input string?

https://code.sololearn.com/cpsJU308T6Xa/#cpp suppose my input is hello ,now it consists of 5 characters.when i call the reversed.size() it outputs 6 why?Am i using wrong function ?

8th Oct 2017, 2:19 PM
shobhit
shobhit - avatar
3 Antworten
+ 4
@Shobhit it's probably because the size method returns the length of the string including the null terminator, hence it gives length+1. Hth, cmiiw
8th Oct 2017, 2:32 PM
Ipang
+ 3
This is simply because you used += on the new string. You see, the string constructor, when called during creation, does not allocate an empty string. Instead, it assigns 1 to your string. (Atleast here on Sololearn it works like this.). Thus, to save the data, you should initialize reversal with "" or clear it. Eg : string reversal = ""; reversal.clear(); If this doesn't work, Try reducing the initial variable to str.length() -1. It seems the loop is copying some variable that doesn't yet exist. Maybe a '\0'... This will solve your problem...
8th Oct 2017, 2:29 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
@Ipang No, size and length are direct synonyms, and both return the same thing : www.cplusplus.com/reference/string/string/size
8th Oct 2017, 3:20 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar