Why 'cin' takes more characters when not used in loop

In the following code if I am typing more than 20 elements then all of them are displyed instead of displaying first 20 elements as the varibale 'ch' is declared to have only 20 elements. I can't understand why this is happening...


char ch[20];
cout<<"Enter any string\n";
cin>>ch;
cout<<ch;
Last edited on
That is undefined behaviour.

You write to outside of the array ch. We have no idea what memory is located after the ch and thus no idea what is overwritten by your input operation.

The same is equally true in a loop, but in your experience the overwritten memory is different.

You are shooting at a target. The bullet goes through the target. You may, or may not have your foot behind the target. Do not feel lucky, if it doesn't hurt.


Do not read into a character array, if you cannot be sure that the input is not too long. Use std::string
Well, strictly speaking it's more the case that you should not read into a character array using cin (or any other type of istream) with the extraction operator (>>).

When reading into a char buffer operator>> takes all chars up until the next whitespace character (space, tab, newline.) It does not check the size of the buffer; so if there are too many chars, the buffer will be overrun.

The string version of operator>> is smarter; it will resize the buffer as required (memory allowing.)

If you are forced to use a buffer (cf. the more usual string) then you can use istream& get (char* s, streamsize n);
http://www.cplusplus.com/reference/istream/istream/get/

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{
    char ch[8]; // use 8 here to make it easier to test
    cout<<"Enter any string\n";
    //cin>>ch;
    cin.get(ch, 8); // use get() rather than >>
    cout<<ch;
    cout<<"\n"; // added this

    return 0;
}


get automatically adds a null terminator to the end of the gotten string, so the maximum length of string is one less than the buffer size (here the buffer is just 8 long, to the max string length is 7.)

Enter any string
1234567890
1234567


Andy
Last edited on
Topic archived. No new replies allowed.