'index of char array is returning ascii values instead of actual char?
I am trying to recreate a simple version of the string class in C++. I am currently having trouble with some functions like the substring() function.
My private member data includes this:
char* chars;
unsigned int size;
And my function definition is here:
FunString FunString::substring(unsigned int a, unsigned int b) const {
//return substring from index a to b
//check if substring is in correct bounds
FunString temp;
for (unsigned int i = a; i < b; i++) {
temp.chars[i] = chars[i];
}
return temp;
}
I am trying to just recreate the classic substring function but when I try this:
int main() {
FunString s = "Hellooooo";
FunString b;
b = s.substring(0,4);
cout << b;
return 0;
}
It outputs this:
Hell└
Any idea what's going on here?
Solution 1:[1]
The problem you have is that you builded temp string properly, but didn't add '\0' at the end. So then printing string you get your string + some things that lay after it in the memory.
FunString FunString::substring(unsigned int a, unsigned int b) const {
FunString temp;
for (unsigned int i = a; i < b; i++) {
temp.chars[i] = chars[i];
}
temp.chars[b] = '\0'; // you should add this line
return temp;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alwyd |
