Converting String to Char

Hello, the code below works but if I remove the " // " to make it no longer a comment and replace the "hello" in the third line with a, it gives me an error.
error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'char*' in initialization|
How can I solve this?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;
int main()
{

    int len = 0;

    //string a = "hello";

    char *s = "hello";
    while(*s != '\0')
    {
        s++;
        len++;
    }
    cout << len;

return 0;
}
put an s on the end.
string a = "hello"s;

not sure why it won't take it without, though.
Last edited on
A c++ string is actually an object of the string class with functions and operators which deal with dynamic memory allocation in the background. It is not actually guaranteed that the data in a string be stored in the same manner as an array.

A line such as char *s; will create a pointer to a single char,
You will also likely run into segmentation faults if you tried to assign a value to (s++), because a char pointer's length is supposed to be treated as a constant. (at least until it is assigned to a new address like the q pointer in the code below)
Like char *s = "Hello" gives you 6 char pointers to play with, assigning a value past that would cause problems.

You can use a char array instead to give yourself a buffer of pointers big enough to deal with, and assign each pointer from an index to the C++ string like this;
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
28
#include <string>
#include <iostream>

using namespace std;

int main()
{
        string h = "hello world";
        char s[12];
        for(int i = 0; i < h.length(); i ++)
        {
                s[i] = h[i];
        }
        cout << s << endl;

        int len = 0;
        char * q;
        q = s;
        while(*q != '\0')
        {
                q ++;
                len ++;
        }
        cout << "After counting:\n";
        cout << q - 11 << endl;
        cout << s << endl;
        cout << len << endl;
}

Sorry, I started playing near the end with that q pointer...

When you get tired of the limitations of creating a static char buffer to work with data of unknown size (Like loading a text file), then it will be time to look into dynamic memory, and/or reading more into the C++ string class.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
    int len = 0;
    string a = "hello";
    
    char *s = new char[a.size()+1];         // +1 for the null-termination
    strcpy( s, a.c_str() );
    
    for ( char *p = s; *p; p++) len++;      // don't move s - it's your only access to dynamically-allocated memory!
    cout << len;
    delete [] s;
}
Last edited on
EDIT: pointless example - I’m deleting it. Sorry.
Last edited on
> error: cannot convert 'std::_string' to 'char*' in initialization|
> How can I solve this?

To get a pointer to the first character of a non-modifiable null-terminated character array
(which is all that is needed here), use std::string::c_str()
https://en.cppreference.com/w/cpp/string/basic_string/c_str

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
    std::string str = "hello" ;

    std::size_t len = 0 ;
    for( const char* ptr = str.c_str() ; *ptr != 0 ; ++ptr ) ++len ;
    std::cout << len << ' ' << str.size() << '\n' ;
    // these two will yield the same value since the string str does not contain an intermediate null character
}

Note: to get a pointer which can be used to modify the characters (before the terminating null character), we have std::string::data()
https://en.cppreference.com/w/cpp/string/basic_string/data
> the code below works but if I remove the " // " (...) it gives me an error.
¿why don't just simply post the code that gives you an error?

> How can I solve this?
if doing x gives you an error, then don't do x
1
2
3
string a = "hello";
a.size(); //it gives you the string length
a.length(); //it also gives you the string length 



> Like char *s = "Hello" gives you 6 char pointers to play with
6 characters, no 6 char pointers,
you can't «play with» it, you may not modify any of those characters
and for that reason char *s = "Hello" is illegal,
and you should write const char s = "Hello"
or char s[] = "Hello" if you plan to modify the string.


for the record, there is a strlen() function.

also, you may do const char *s = a.c_str();
Thank you ne55, I didn't realize exactly what char * s = "strings" was doing. It's very constant. So much so that I get a warning when I try to compile it in g++;

testStr.cpp: In function ‘int main()’:
testStr.cpp:9:19: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    9 |         char *s = "Hello";

I must have had warnings turned off while I was using the online compiler. Have placed a strike-through in that sentence above.

Last edited on
Oh... haha.. I really misread the problem there.
I thought you were getting the error on just putting a quoted string into a string variable, not the subsequent code that is hosed up.
so you have to explicitly add the zero which my idea would do:
string a = "hello\0"s; //this will allow your code to work. You still should not go there, but it forces the terminal zero to be placed.

string does not use zero terminals, you can in fact do this for fun:
string a = "hello\0world"s;
cout << a.c_str() << endl; //hello
cout << a << endl; //hello world, and on my terminal, the 0 looks like a space but isn't.
I used to do a lot of hands-on C string and found out when I moved to strings that you can't mix the two carelessly.
Last edited on
> Note: to get a pointer which can be used to modify the characters (before the terminating null character),
> we have std::string::data()
> https://en.cppreference.com/w/cpp/string/basic_string/data
constexpr CharT* data() noexcept; //(since C++20)
not anymore, it seems
Last edited on
Topic archived. No new replies allowed.