Abhishek Agrawal Abhishek Agrawal -3 years ago 65
C++ Question

Shifting the pointer of the string in C++

In C we are able to do this :

char *str;
scanf("%s", str); // lets say that we enter "Hello"
str = str + 2;
printf("%s", str); // and the answer would be "llo"

Is there something like this in C++ with string datatype in O(1) time?

Edit : It is giving me this error ->

error: invalid operands to binary expression ('string' (aka 'basic_string<char,
char_traits<char>, allocator<char> >') and 'int')
str = str + 1;

Edit2 : I ran this code and got the above error ->

string str = "Hello";
str = str + 1;
cout << str << endl;

Answer Source
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "foobar";
    cout << &s[s.size() - 2] << endl;
    cout << &s[3] << endl;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download