Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ .length() function giving wrong results

Tags:

c++

string

My code that analyzes a string is printing incorrect number of positions in integers. The result is initially off by 1 integer, and when I insert a char to the string, the result changes by 2 position values even though I only added one char. Here is the code:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main(){
    string s1 = "Hey, what's up?";
    cout << s1.length() << endl; // should be 14 positions, not 15 if starting at 0
    cout << s1.insert(1, "k") << endl;
    s1 = s1.insert(1, "k");
     cout << s1.length() << endl; //should be 15, not 17
    system("pause");
    return 0;
}

Please tell me why .length() is not printing the correct number of positions.

like image 1000
Haris Irshad Avatar asked Feb 24 '26 12:02

Haris Irshad


1 Answers

.length() does not return the end position of the string, it returns the number of elements in the string. ie. "four" will be 4 because it has four letters.

std::string four = "four";
std::cout << four.length() << std::endl;

output:

4

The reason that the return for the second part is 17 and not 16, is because you insert k twice, once in your std::cout and a second time later in the code. Your actual output string will be this:

Hkkey, what's up?
like image 121
Fantastic Mr Fox Avatar answered Feb 26 '26 02:02

Fantastic Mr Fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!