Strlen() always returns 6 or 0!

Hello All,
I am trying to count the number of characters in a user entered string. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <string.h>
using namespace std;

const char *get_c_string();

int main()
{
    const char *user_string;
    cout << setw(3) << "Enter a string: ";
    user_string= get_c_string();

    cout << strlen(user_string) << endl;

    return 0;
}

const char *get_c_string()
{
    string str;
    getline(cin, str);

    const char *s= str.c_str();
    return s;
}


No matter what I enter, I strlen() returns 0 or 6! And it seems to be random. "Hello world" might return 6 one time, and 0 another.
Please help if you can. Thanks

Edit:
I found a work-around, but I am not sure why this works and the original does not. Here is my new code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
    string user_string;
    const char *user_c_string;
    cout << setw(3) << "Enter a string: ";
    getline(cin, user_string);

    user_c_string= user_string.c_str();

    cout << strlen(user_c_string) << endl;

    return 0;
}


Last edited on
closed account (48T7M4Gy)
You need a ; at the end of line 15

Other than that I tested your program using the shell here and it works OK

Enter a string: as
2


Enter a string: Hello world
11
Last edited on
Sorry about the missing semi-colon. I actually do have it in my main program. For some reason, I'm still getting 6 or 0. Any ideas?
Topic archived. No new replies allowed.