Jump to content

[NEWBIE ALERT] Why is my simple/stupid/pointless C program not working right?

- - - - -

  • Please log in to reply
8 replies to this topic

#1
adriangb

adriangb

    Newbie

  • Members
  • Pip
  • 4 posts
My code:
#include <stdio.h>


main () {

    int x, r, attempts;

	char c, c2;

	x = 10;

	printf("\nHello, World! %d \n", x);

	printf("Did it work? (y/n)\n");

	c = getchar();

	putchar(c);

	while (c!= 'n' && c!= 'y' && c!= 'n' && c!= 'N' && c!= 'Y') {

		printf("\nYou entered an invalid character, try again\n");

		c = getchar();

	}

	if (c== 'n' || c== 'N') {

		printf("\nThat sucks!");

		r = 0;

	}

	if (c == 'y' || c == 'Y') {

		printf("\nRock on!");

		r = 1;

	}

	while (r == 0) {

		printf("\nUghh, I (or you for that matter), failed. Try again (y/n)?\n");

		c2 = getchar();

		putchar(c2);

		if (c2== 'n' || c2== 'N') {

			printf("\nThat's too bad!\n");

		}

		if (c2== 'y' || c2== 'Y') {

			printf("\nOk, I'll run main again!\n");

			++attempts;

			r = 1;

			main ();

		}

	}

	printf("\nThe total number of attempts necessary where %d\n", attempts);

	return (attempts);

}

Issues: ?? I don't know exactly what's wrong (or I wouldn't be asking ;) ), but here is sample output:

Quote

Hello, World! 10
Did it work? (y/n)
n

That sucks!
Ughh, I (or you for that matter), failed. Try again (y/n)?

Ughh, I (or you for that matter), failed. Try again (y/n)?
y

Ok, I'll run main again!

Hello, World! 10
Did it work? (y/n)

You entered an invalid character, try again
y

Rock on!
The total number of attempts necessary where 121

The total number of attempts necessary where 122


#2
Simonxz

Simonxz

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
You need to clear your buffer

#3
adriangb

adriangb

    Newbie

  • Members
  • Pip
  • 4 posts
What does that mean/who do I do it?
Thanks for the reply

#4
Simonxz

Simonxz

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
use fflush(stdin) in your while loop, the messages won't pop up twice anymore

#5
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
First you have not initialized the variables you are working with! Incrementing "int attempts" will increment a random memory value and result in a random number. Initialize all your variables you are using to zero first.

By clearing the buffer, he means getchar() will get a char, but when you type in a letter and press enter, the enter (newline, or '\n' character) is still in the buffer, so you must run getchar() or fflush(stdin) after each getchar.

Also, if you run main() in the function, it will display attempts, and then break out in to parent main() and display attempts again, so I would recommend you do not call it like that.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#6
adriangb

adriangb

    Newbie

  • Members
  • Pip
  • 4 posts

Alexander said:

First you have not initialized the variables you are working with! Incrementing "int attempts" will increment a random memory value and result in a random number. Initialize all your variables you are using to zero first.

By clearing the buffer, he means getchar() will get a char, but when you type in a letter and press enter, the enter (newline, or '\n' character) is still in the buffer, so you must run getchar() or fflush(stdin) after each getchar.

I thought integers defaulted to 0... Anyways, I added r = attempts = 0;

I thought the "Enter" might be making a mess, but of course I could't possibly explain why or how to fix it. But what I don't get is where to put the fflush(stdin), I tried the following and it didn't work (edited it, I had missed one, and I added above and below to try...):
main () {

    int x, r, attempts;

	char c;

	x = 10;

	r = attempts = 0;

	printf("\nHello, World! %d \n", x);

	printf("Did it work? (y/n)\n");

	fflush(stdin);

	c = getchar();

	fflush(stdin);

	while (c!= 'n' && c!= 'y' && c!= 'n' && c!= 'N' && c!= 'Y') {

		printf("\nYou entered an invalid character, try again\n");

		fflush(stdin);

		c = getchar();

		fflush(stdin);

	}

	if (c== 'n' || c== 'N') {

		printf("\nThat sucks!");

		r = 0;

	}

	if (c == 'y' || c == 'Y') {

		printf("\nRock on!");

		r = 1;

	}

	while (r == 0) {

		printf("\nUghh, I (or you for that matter), failed. Try again (y/n)?\n");

		fflush(stdin);

		c = getchar();

		fflush(stdin);

		if (c== 'n' || c== 'N') {

			printf("\nThat's too bad!\n");

		}

		if (c== 'y' || c== 'Y') {

			printf("\nOk, I'll run main again!\n");

			++attempts;

			r = 1;

			main ();

		}

	}

	printf("\nThe total number of attempts necessary where %d\n", attempts);

	return (attempts);

}



#7
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
You only need to place it after getchar();

You can see an example for yourself with this code what happens:
char a, b;
a = getchar(); //you would type a letter here
b = getchar();

if(b == '\n') {
   printf("A newline is in b");
}
As you may suspect, a newline automatically populates b, the same thing happens in your code, we can fix this by placing fflush(stdin) after "a = getchar();" so 'b' can accept an actual character. You are essentially flushing the standard input (stdin) of the newline.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#8
adriangb

adriangb

    Newbie

  • Members
  • Pip
  • 4 posts

Alexander said:

You only need to place it after getchar();

You can see an example for yourself with this code what happens:
char a, b;
a = getchar(); //you would type a letter here
b = getchar();

if(b == '\n') {
   printf("A newline is in b");
}
As you may suspect, a newline automatically populates b, the same thing happens in your code, we can fix this by placing fflush(stdin) after "a = getchar();" so 'b' can accept an actual character. You are essentially flushing the standard input (stdin) of the newline.

It's not working or me, I tried this for example:
#include <stdio.h>

int main () {
    char a, b;
    a = getchar(); //you would type a letter here
    fflush(stdin);
    b = getchar();
    fflush(stdin);
    if(b == '\n') {
        printf("A newline is in b");
    }
}
Output:

Quote

f
A newline is in b
I think I understood it thou: I enter f and \n (aka enter). f is taken by getchar() and written to a, and \n stays in the buffer (ie, it's "the next character in line")
So when I call getchar() again, it grabs the first charachter in line (in this case "\n") and writes it to b.

Edited by Alexander, 11 March 2011 - 01:19 PM.
Fixed bbcode for [code


#9
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Are you sure you typed two separate chars rather than pressing enter on the second one?
a
b
Press enter to continue...
That is good though that you get the concept! I see you have added the fflushes to your original code (although you just need it below the getchars not above)

Your only problem now is calling main() twice, I would rewrite the application to be in a while loop, and that while loop checking if c == no or yes, then an inner loop dealing if it is no to ask to try again.

You could also put the whole part inside a function (check()) and at the end display attempts, this is a lot better than calling main again.

Edited by Alexander, 11 March 2011 - 01:59 PM.

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users