![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#11 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Don't use gets. There are explanations on the forum (which is why searching is recommended), but here's the short form: you have no control over how much your user enters; hence, you're liable to overrun the buffer and cause Bad Thangs to happen. "Fgets" allows you to specify a maximum size of input, which you match to your buffer length (read the docs to understand about when input stops and the automatic addition of a terminating zero, requiring one additional element in the buffer). Stdin is an input stream that is initially opened and set to the console input when your program is executed. Since "fgets" can deal with any stream, you must specify which one you want.
Jim specified why he showed decrement "len". Read your responses and read the documentation associated with the things you use. In short, array elements number from zero. A four-byte string line "abcd" would occupy elements 0, 1, 2, and 3. The terminating zero, if it's a C-string, will occupy element 4. "Strlen" gives you the length of the string, not counting the nul byte. If the length is 4, the position of the fourth character will be element 3. Thus the decrement.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#12 |
|
Newbie
Join Date: Oct 2005
Posts: 17
Rep Power: 0
![]() |
Ok, so that's how those work.
Gawd I'm such a n00b at this. Ok, so I appended the program so it includes fgets and the decrementer. When I enter say 'diary', I get: Please enter a noun(up to 28 characters) to pluarize:diary 5 diary s is the plural. Also diary should be 'diaries' not 'diarys' are the if statements messed up still? |
|
|
|
|
|
#13 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
IF fgets terminates input because of a newline (rather than exceeding a specified length or encountering EOF), it includes the newline in the string. Test element number (strlen-1) for '\n' and if you find it, overwrite it with a zero, '\0'. The length of the string will then be one less (which you would find if you used strlen again). If you actually took my advice to read the documentation, you didn't pay enough attention. I suggest you try it again. No one blames you for being a newbie; reading the docs for what you use will go a long way, arm in arm with time, towards correcting that.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|