Pointer to a C ++ string

in the following code, I use a pointer to a C ++ string in the change () function.

In any case, should you use string class operators when working with a pointer to a string? For example, at () works for the [] operator, but is there a way to use the [] operator?

#include <string>
#include <iostream>

using namespace std;

void change(string * s){

    s->at(0) = 't';
    s->at(1) = 'w';
    // s->[2] = 'o'; does not work
    // *s[2] = 'o'; does not work


}

int main(int argc,char ** argv){

    string s1 = "one";

    change(&s1);

    cout << s1 << endl;

    return 0;
}
+3
source share
4 answers

Split it up:

(*myString)[4]

But, can I suggest instead of a pointer using the link:

void change(string &_myString){
    //stuff
}

Thus, you can use everything that would be with the object.

+12
source

If you encounter operator priority, try

(*s)[0]
+6
source

:

s->operator[](2) = 'o';
+5

, std::string , . -, , :

(*s)[i]

:

void change( string &s )
{
    s.at(0) = 't';
    s.at(1) = 'w';
    s[2] = 'o';
    s[2] = 'o';    
}

.

+3
source

Source: https://habr.com/ru/post/1764980/


All Articles