1

I am currently writing a C++ program on Xcode. The following is a snippet of the code I am running:

char myString[3];
cin >> myString;
cout << myString << endl;

The code is very straightforward. However, when I enter strings longer than 2 characters, the string still accepts them. Why doesn't the string only store two characters plus the null terminator?

Thanks!

1 Answer 1

2

Because it can't. When you pass an array into a function (operator>> counts!) by value, you're really just passing a pointer to the array. A char* doesn't know the size of the buffer it points to.

In theory the standard library could have been designed so that it had a function template taking a reference to the array, like:

template <size_t N>
operator>>(char (&input)[N]);

But, well, it just doesn't. You could propose its addition to the C++ standards committee.

Anyway, there's no need for formatted extraction here. Prefer something like:

cin.read(&myString[0], sizeof(myString)-1);

…or use an actual string.

Sign up to request clarification or add additional context in comments.

2 Comments

@xskxzr: Heh... habit.
Nearly all of my "dang, nearly" compilation errors after coding for a while, are when I sprinkled const where I shouldn't've.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.