tags:

views:

273

answers:

8
#include <iostream>
using namespace std;

typedef struct
{
    char streetName[5];

} RECORD;

int main()
{
    RECORD r;
    cin >> r.streetName;
    cout << r.streetName << endl;

}

When I run this program, if I enter in more than 5 characters, the output will show the whole string I entered. It does not truncate at 5 characters. Why is that?

How can I get this to work correctly?

+5  A: 

Because you're overruning the end of your buffer and in this particular case you're getting away with it. C and C++ make it very easy to "shoot yourself in the foot", but that doesn't mean that you should.

Paul R
+3  A: 

It's a buffer overrun.

Nikolai N Fetissov
+11  A: 

You are overflowing the buffer. Put another char array after streetName and you will likely find that it gets the rest of the characters. Right now you are just corrupting some memory on your stack.

twk
+5  A: 

Because cin sees streetName as a char * and writes to memory and there is nothing to stop writing to *(streetName + 6) and further. This is a form of buffer overrun

The best code in this case is define streetName as a std::string

i.e.

typedef struct
{
        std::string streetName;
} RECORD;
Mark
+3  A: 

The way to do this correctly in c++ is to use a std::string.

#include<iostream>
#include<string>

....
std::string r;
getline(cin, r);
std::cout << r <<std::endl;

For truncated input(with suitably defined and inited values).

while(cin.peek() != EOF && i < len)
{
  cin >> arr[i];
  ++i;
}

You will want to do something after this to flush the buffer and not leave the rest of the line sitting on the input stream if you plan on doing other things with it.

stonemetal
He posted his add on after I answered.
stonemetal
+2  A: 

C++ does not perform bounds checking on array accesses, and memory does not simply stop at the end of the array. You are writing data to memory that is not part of the array, the consequences of which are non-deterministic, and may sometimes even appear to work.

It is quite likely that if you placed that code into a function, the program would crash when you tried to return from the function, because one likely possibility is that you will have dumped on the function return address on the stack. You may also have corrupted data belonging to the calling function.

Clifford
+3  A: 

Use

cin.getline(r.streetName, 5);

Note that the last character is the end-of-string character. In other words, if you want to enter five characters, you need an array of length six.

Christian Jonassen
+6  A: 

In order to limit the input to the size of the receiving array you need to use the length-limiting facilities provided by your input method. In your case you are using cin, which means that you can specify the limit by using its width method

cin.width(5);    
cin >> r.streetName;
AndreyT