JK> I used to program in C and used an array of chars for strings, Now I'm
JK> using C++ and find that strings are now a class with shinny new
JK> operations to preform on them. However I have a few questions about
JK> using the old C style strings in C++.
JK> For various reasons there are times when I need to use an array of
JK> chars for a string. Can I safely use cin on it? for example, is cin <<
JK> somestring; safe?
Somewhat. You do need to make sure that the buffer you've allocated
is large enough.
JK> By safe I mean that The array has to have a null char
JK> in it to terminate it.
If you've got enough space allocated, you'll get a zero byte tacked
on.
JK> If the char array is 5 elemets and someone types
JK> in a huge string what will happen?
Almost anything.
JK> I'm assuming since cin doesnt know
JK> the size of my array that it will just write all thoese bytes over
JK> whatever happens to be in memory after the array of chars.
Correct.
JK> Also, I need a bit of a refresher course with char array strings, One
JK> point I can't quite remember is the max length of a string that can be
JK> entered into an arary of a given size, is it size-1? For example, if an
JK> array has 3 elements (0-3) I cannot store "the" as there will be no
JK> null character, but "hi" is ok as it would be "Hi"+nullch (3 elements)
Since you are defining 'string' to include the zero terminating byte,
you've got it exactly right. The string 'the' requires 4 bytes of
storage. If you try to stuff it into 3 bytes, the 'the' gets stored
and where the zero has gone is anyone's guess.
---
þ Blue Wave/QWK v2.12 þ
---------------
* Origin: St. Louis Users Group (1:100/4)
|