Debug Assertion Failure on gets(char) function

R

Richard Heathfield

Army1987 said:
"Richard Heathfield" ha scritto...
if(fgets(Yes_No, sizeof Yes_No, stdin) != NULL && Yes_No[0] == 'y')

Is it necessary?

No, of course not. There are plenty of ways you could do this...
I'd just use:
int answer;
int ch;

and then:
answer = getchar();
do {
ch = getchar();
} while (ch != '\n' && ch != EOF);
if (answer == 'y' || answer == 'Y') {

....for example, you could write five lines of code instead of one, and
still fail to deal with EOF correctly.
 
A

Army1987

Richard Heathfield said:
Army1987 said:
"Richard Heathfield" ha scritto...
if(fgets(Yes_No, sizeof Yes_No, stdin) != NULL && Yes_No[0] == 'y')

Is it necessary?

No, of course not. There are plenty of ways you could do this...
I'd just use:
int answer;
int ch;

and then:
answer = getchar();
do {
ch = getchar();
} while (ch != '\n' && ch != EOF);
if (answer == 'y' || answer == 'Y') {

...for example, you could write five lines of code instead of one, and
still fail to deal with EOF correctly.

Why?
If the user sends an EOF to stdin when asked for an answer, the
program does the same as if he wrote "No!" and pressed enter, or
if he wrote "0" and pressed enter.
(Note that your program prints "Couldn't read your answer.\n" to
stderr in any of these cases, or even if the user writes "Yes.".
And it even returns 0. Also, it doesn't discard any character from
the (sizeof Yes_No)th onwards on the line. What happens if I write
y supercalifragilisticexpialidocious.txt, and the file
ilisticexpialidocious.txt can successfully be opened?)

If the line count means anything, then

answer = getchar(); do { ch = getchar(); } while (ch != '\n' && ch != EOF);
if (answer == 'y' || answer == 'Y') {
would be better.

(Or:
if (scanf("%c%*[^\n]%*c", &ans) > 0 && ans && strchr("Yy", ans)) {
where ans is an unsigned char, and string.h has been included... )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top