imran
imran

Reputation: 88

What is cin>>str+1 in C++ string?

char str[80];
cin >> str+1;
cout << str+1;

What does this +1 mean? How does it work? Any help would be appreciated. Thanks for reply.

Upvotes: 3

Views: 2078

Answers (2)

It's pointer arithmetic. str is an array of 80 chars. C++ supports an implicit array-to-pointer conversion, which means that in most expressions, str is automatically converted to a char *. + 1 is then applied to that pointer, yielding the same address as &str[1].

cin >> str+1;

This reads from standard input, storing the result in the buffer starting at str[1](1).

cout << str+1;

This writes to standard output starting from str[1] and onwards until the NUL terminator(2).

In effect, the operations just ignore the first element of the array str.


(1) Notice that there is no bounds checking. If the input is longer than 78 characters (80 - 1 for the first char - 1 for the NUL terminator), Undefined Behaviour (most likely a buffer overrun) will happen.

(2) If there is no NUL terminator in the array, Undefined Behaviour will occur again.

Upvotes: 8

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

In expression str + 1 character array str is converted to pointer to its first element. Thus str + 1 is pointer to the second element of the array.

That it would be more clear consider a simple program

#include <iostream>

int main()
{
    char s[] = "Hello";

    for ( size_t i = 0; *( s + i ) != '\0'; ++i )
    {
        std::cout << s + i << std::endl;
    }
}

The program output will be

Hello
ello
llo
lo
o

Upvotes: 1

Related Questions