DV> If you do that verbatim, you will have an overflow
DV> problem with all known compilers. This is how that
DV> should be:
DV> char name[40];
DV> gets(name);
DV> name[40]='\n';
DV> You have to put a NULL on the end or it will have an
DV> overflow problem. I believe you have to do that with
DV> 'fgets' as well..
Don't try this at home!
Since name has only 40 elements, name[39] is the last
one you can access. Accessing name[40] with an assignment
operation writes a value to an unknown location. Rather, we
KNOW where it writes it, but have no idea what SHOULD be
there. This can crash your system. You don't need '\n' at
the end of your string, and will often wish to strip it off
when using gets() or fgets(). You want a NUL, or zero
terminator, which is '\0', which gets() and fgets() will also
automatically assign. It is things like this which made the
stream libraries necessary, as the I/O usage is confusing at
best, and can absolutely bewilder the beginner.
istream getname;
char name[40];
getname.getline(name, 40);
or
char name[40];
fgets(name, 40, stdin);
if(strchr(name, '\n'))
{
*strchr(name, '\n') = '\0';
}
else
{
char buf[16] = "";
do {
fgets(buf, 16, stdin);
} while(!strchr(buf, '\n'));
}
You WILL have to strip the '\n' from that second example,
which is C and not C++, since it ignores stream objects and
uses standard C functions instead. You also need to see if
the '\n' made it into the string or if it remained in the
stream buffer and needs to be flushed from it.
You can see how the C++ version would be much preferred for
quick development and simplified maintenance.
---
> ] Wait a minute... ///\oo/\\\ Almonds don't have legs.........
---
---------------
* Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)
|