unexpected output with getchar() - c

char c = ' ';
while(c != 'x')
{
c = getchar();
printf("threadFuncParam = %u\n", threadFuncParam);
}
In the above code snippet the print is printing threadFuncParam value twice every time I enter a character where as I expect it to print only once.
As per my understanding very first time it enters while as condition is true and and then wait for user input at getchar call on entering a character it shall print the value and then if input character is not x it shall wait for another input at getchar call, but whenever i enter a character i see 2 prints ion screen for each input. I am not able to understand why?
What i'm trying to do here is that in main thread i am taking single char input from user and in worker thread i am incrementing a counter which gets incremented every second, i print the value everytime user input a char input until user enters 'x' character.

The simple issue here is that the console (input) sends the text to the stdin only when it encounters a enter key or ctr+d.
As a result an extra \n goes into your input stream. This causes your program to read that character in the next iteration.
A simple solution would be to read all white space characters in the stream.
This can be done in multiple ways -
If you need to discard any whitespace characters (including space, tabs, vtabs, newline), you can add
scanf(" ");
before the getchar();
If you need to discard only the newlines which come as a result of pressing enter, you can add
scanf("%*[\n]")
before the getchar();
This will eat up all the \n that come before the next character. But will not eat spaces.
Finally if you want to discard only 1 \n
You can do
scanf("%*1[\n]");
Remember though, in all the cases the scanf should be immediately before the getchar() because scanf would wait till it finds the next non white space character.
All cases figured out with the help of comments from #chux.

If you tried to debug your program (its best way to learn to code), you would spot that the second value is everytime 10. In ASCII table you would find that is code for new line. Which you are pressing after the every character. Then by fast & simple searching you would find this THREAD. Where is the problem described and you would easily solve it.
char c = ' ';
while(c != 'x')
{
printf("threadFuncParam = %u\n", (char)c);
fflush(stdout);
if (scanf(" %c",&c) != 1)
{
// failed
}
}

I think the problem is in the way logic is applied. You print before you check the condition. See this for explanation:
loop 1: getchar() executed say for value 'a'.
printf() executed.
loop 2: Because c='a', condition is true. Now, getchar() is executed with 'x' value.
printf() is again executed.
loop 3: Condition is evaluated false. Loop is terminated.
So basically you should change your logic a little bit.

Related

Program ends before I type A or D for bubble sorting [duplicate]

I'm trying to develop a simple text-based hangman game, and the main game loop starts with a prompt to enter a guess at each letter, then goes on to check if the letter is in the word and takes a life off if it isn't. However, when I run the game the prompt comes up twice each time, and the program doesn't wait for the user's input. It also takes off a life (one life if it was the right input, two if it wasn't), so whatever it's taking in isn't the same as the previous input. Here's my game loop, simplified a bit:
while (!finished)
{
printf("Guess the word '%s'\n",covered);
scanf("%c", &currentGuess);
i=0;
while (i<=wordLength)
{
if (i == wordLength)
{
--numLives;
printf("Number of lives: %i\n", numLives);
break;
} else if (currentGuess == secretWord[i]) {
covered[i] = secretWord[i];
secretWord[i] = '*';
break;
}
++i;
}
j=0;
while (j<=wordLength)
{
if (j == (wordLength)) {
finished = 1;
printf("Congratulations! You guessed the word!\n");
break;
} else {
if (covered[j] == '-') {
break;
}
}
++j;
if (numLives == 0) {
finished = 1;
}
}
}
I assume the problem is scanf thinking it's taken something in when it hasn't, but I have no idea why. Does anyone have any idea? I'm using gcc 4.0.1 on Mac OS X 10.5.
When you read keyboard input with scanf(), the input is read after enter is pressed but the newline generated by the enter key is not consumed by the call to scanf(). That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf() call return instantly with no data).
To avoid this, you can modify your code to something like:
scanf("%c%*c", &currentGuess);
The %*c matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call scanf() you are starting with an empty input buffer.
Caveat: If the user presses two keys and then presses enter, scanf() will return the first keystroke, eat the second, and leave the newline for the next input call. Quirks like this are one reason why scanf() and friends are avoided by many programmers.
Newlines.
The first time through the loop, scanf() reads the character.
Then it reads the newline.
Then it reads the next character; repeat.
How to fix?
I seldom use scanf(), but if you use a format string "%.1s", it should skip white space (including newlines) and then read a non-white space character. However, it will be expecting a character array rather than a single character:
char ibuff[2];
while ((scanf("%.1s", ibuff) == 1)
{
...
}
Break the problem up into smaller parts:
int main(void) {
char val;
while (1) {
printf("enter val: ");
scanf("%c", &val);
printf("got: %d\n", val);
}
}
The output here is:
enter val: g
got: 103
enter val: got: 10
Why would scanf give you another '10' in there?
Since we printed the ASCII number for our value, '10' in ASCII is "enter" so scanf must also grab the "enter" key as a character.
Sure enough, looking at your scanf string, you are asking for a single character each time through your loop. Control characters are also considered characters, and will be picked up. For example, you can press "esc" then "enter" in the above loop and get:
enter val: ^[
got: 27
enter val: got: 10
Just a guess, but you are inputting a single character with scanf, but the user must type the guess plus a newline, which is being consumed as a separate guess character.
scanf(" %c", &fooBar);
Notice the space before the %c. This is important, because it matches all preceding whitespace.
Jim and Jonathan have it right.
To get your scanf line to do what you want (consume the newline character w/o putting it in the buffer) I'd change it to
scanf("%c\n", &currentGuess);
(note the \n)
The error handling on this is atrocious though. At the least you should check the return value from scanf against 1, and ignore the input (with a warning) if it doesn't return that.
A couple points I noticed:
scanf("%c") will read 1 character and keep the ENTER in the input buffer for next time through the loop
you're incrementing i even when the character read from the user doesn't match the character in secretWord
when does covered[j] ever get to be '-'?
I'll guess: your code is treating a newline as one of the guesses when you enter data. I've always avoided the *scanf() family due to uncontrollable error handling. Try using fgets() instead, then pulling out the first char/byte.
I see a couple of things in your code:
scanf returns the number of items it read. You will probably want to handle the cases where it returns 0 or EOF.
My guess would be that the user is hitting letter + Enter and you're getting the newline as the second character. An easy way to check would be to add a debugging printf statement to show what character was entered.
Your code will only match the first occurrence of a match letter, i.e. if the word was "test" and the user entered 't', your code would only match the first 't', not both. You need to adjust your first loop to handle this.
When you enter the character, you have to enter a whitespace character to move on. This whitespace character is present in the input buffer, stdin file, and is read by the scanf() function.
This problem can be solved by consuming this extra character. This can be done by usnig a getchar() function.
scanf("%c",&currentGuess);
getchar(); // To consume the whitespace character.
I would rather suggest you to avoid using scanf() and instead use getchar(). The scanf()requires a lot of memory space. getchar() is a light function. So you can also use-
char currentGuess;
currentGuess=getchar();
getchar(); // To consume the whitespace character.

Why the print is happening two times [duplicate]

I'm trying to develop a simple text-based hangman game, and the main game loop starts with a prompt to enter a guess at each letter, then goes on to check if the letter is in the word and takes a life off if it isn't. However, when I run the game the prompt comes up twice each time, and the program doesn't wait for the user's input. It also takes off a life (one life if it was the right input, two if it wasn't), so whatever it's taking in isn't the same as the previous input. Here's my game loop, simplified a bit:
while (!finished)
{
printf("Guess the word '%s'\n",covered);
scanf("%c", &currentGuess);
i=0;
while (i<=wordLength)
{
if (i == wordLength)
{
--numLives;
printf("Number of lives: %i\n", numLives);
break;
} else if (currentGuess == secretWord[i]) {
covered[i] = secretWord[i];
secretWord[i] = '*';
break;
}
++i;
}
j=0;
while (j<=wordLength)
{
if (j == (wordLength)) {
finished = 1;
printf("Congratulations! You guessed the word!\n");
break;
} else {
if (covered[j] == '-') {
break;
}
}
++j;
if (numLives == 0) {
finished = 1;
}
}
}
I assume the problem is scanf thinking it's taken something in when it hasn't, but I have no idea why. Does anyone have any idea? I'm using gcc 4.0.1 on Mac OS X 10.5.
When you read keyboard input with scanf(), the input is read after enter is pressed but the newline generated by the enter key is not consumed by the call to scanf(). That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf() call return instantly with no data).
To avoid this, you can modify your code to something like:
scanf("%c%*c", &currentGuess);
The %*c matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call scanf() you are starting with an empty input buffer.
Caveat: If the user presses two keys and then presses enter, scanf() will return the first keystroke, eat the second, and leave the newline for the next input call. Quirks like this are one reason why scanf() and friends are avoided by many programmers.
Newlines.
The first time through the loop, scanf() reads the character.
Then it reads the newline.
Then it reads the next character; repeat.
How to fix?
I seldom use scanf(), but if you use a format string "%.1s", it should skip white space (including newlines) and then read a non-white space character. However, it will be expecting a character array rather than a single character:
char ibuff[2];
while ((scanf("%.1s", ibuff) == 1)
{
...
}
Break the problem up into smaller parts:
int main(void) {
char val;
while (1) {
printf("enter val: ");
scanf("%c", &val);
printf("got: %d\n", val);
}
}
The output here is:
enter val: g
got: 103
enter val: got: 10
Why would scanf give you another '10' in there?
Since we printed the ASCII number for our value, '10' in ASCII is "enter" so scanf must also grab the "enter" key as a character.
Sure enough, looking at your scanf string, you are asking for a single character each time through your loop. Control characters are also considered characters, and will be picked up. For example, you can press "esc" then "enter" in the above loop and get:
enter val: ^[
got: 27
enter val: got: 10
Just a guess, but you are inputting a single character with scanf, but the user must type the guess plus a newline, which is being consumed as a separate guess character.
scanf(" %c", &fooBar);
Notice the space before the %c. This is important, because it matches all preceding whitespace.
Jim and Jonathan have it right.
To get your scanf line to do what you want (consume the newline character w/o putting it in the buffer) I'd change it to
scanf("%c\n", &currentGuess);
(note the \n)
The error handling on this is atrocious though. At the least you should check the return value from scanf against 1, and ignore the input (with a warning) if it doesn't return that.
A couple points I noticed:
scanf("%c") will read 1 character and keep the ENTER in the input buffer for next time through the loop
you're incrementing i even when the character read from the user doesn't match the character in secretWord
when does covered[j] ever get to be '-'?
I'll guess: your code is treating a newline as one of the guesses when you enter data. I've always avoided the *scanf() family due to uncontrollable error handling. Try using fgets() instead, then pulling out the first char/byte.
I see a couple of things in your code:
scanf returns the number of items it read. You will probably want to handle the cases where it returns 0 or EOF.
My guess would be that the user is hitting letter + Enter and you're getting the newline as the second character. An easy way to check would be to add a debugging printf statement to show what character was entered.
Your code will only match the first occurrence of a match letter, i.e. if the word was "test" and the user entered 't', your code would only match the first 't', not both. You need to adjust your first loop to handle this.
When you enter the character, you have to enter a whitespace character to move on. This whitespace character is present in the input buffer, stdin file, and is read by the scanf() function.
This problem can be solved by consuming this extra character. This can be done by usnig a getchar() function.
scanf("%c",&currentGuess);
getchar(); // To consume the whitespace character.
I would rather suggest you to avoid using scanf() and instead use getchar(). The scanf()requires a lot of memory space. getchar() is a light function. So you can also use-
char currentGuess;
currentGuess=getchar();
getchar(); // To consume the whitespace character.

using scanf() in a function doesn't work as expected [duplicate]

I'm trying to develop a simple text-based hangman game, and the main game loop starts with a prompt to enter a guess at each letter, then goes on to check if the letter is in the word and takes a life off if it isn't. However, when I run the game the prompt comes up twice each time, and the program doesn't wait for the user's input. It also takes off a life (one life if it was the right input, two if it wasn't), so whatever it's taking in isn't the same as the previous input. Here's my game loop, simplified a bit:
while (!finished)
{
printf("Guess the word '%s'\n",covered);
scanf("%c", &currentGuess);
i=0;
while (i<=wordLength)
{
if (i == wordLength)
{
--numLives;
printf("Number of lives: %i\n", numLives);
break;
} else if (currentGuess == secretWord[i]) {
covered[i] = secretWord[i];
secretWord[i] = '*';
break;
}
++i;
}
j=0;
while (j<=wordLength)
{
if (j == (wordLength)) {
finished = 1;
printf("Congratulations! You guessed the word!\n");
break;
} else {
if (covered[j] == '-') {
break;
}
}
++j;
if (numLives == 0) {
finished = 1;
}
}
}
I assume the problem is scanf thinking it's taken something in when it hasn't, but I have no idea why. Does anyone have any idea? I'm using gcc 4.0.1 on Mac OS X 10.5.
When you read keyboard input with scanf(), the input is read after enter is pressed but the newline generated by the enter key is not consumed by the call to scanf(). That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf() call return instantly with no data).
To avoid this, you can modify your code to something like:
scanf("%c%*c", &currentGuess);
The %*c matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call scanf() you are starting with an empty input buffer.
Caveat: If the user presses two keys and then presses enter, scanf() will return the first keystroke, eat the second, and leave the newline for the next input call. Quirks like this are one reason why scanf() and friends are avoided by many programmers.
Newlines.
The first time through the loop, scanf() reads the character.
Then it reads the newline.
Then it reads the next character; repeat.
How to fix?
I seldom use scanf(), but if you use a format string "%.1s", it should skip white space (including newlines) and then read a non-white space character. However, it will be expecting a character array rather than a single character:
char ibuff[2];
while ((scanf("%.1s", ibuff) == 1)
{
...
}
Break the problem up into smaller parts:
int main(void) {
char val;
while (1) {
printf("enter val: ");
scanf("%c", &val);
printf("got: %d\n", val);
}
}
The output here is:
enter val: g
got: 103
enter val: got: 10
Why would scanf give you another '10' in there?
Since we printed the ASCII number for our value, '10' in ASCII is "enter" so scanf must also grab the "enter" key as a character.
Sure enough, looking at your scanf string, you are asking for a single character each time through your loop. Control characters are also considered characters, and will be picked up. For example, you can press "esc" then "enter" in the above loop and get:
enter val: ^[
got: 27
enter val: got: 10
Just a guess, but you are inputting a single character with scanf, but the user must type the guess plus a newline, which is being consumed as a separate guess character.
scanf(" %c", &fooBar);
Notice the space before the %c. This is important, because it matches all preceding whitespace.
Jim and Jonathan have it right.
To get your scanf line to do what you want (consume the newline character w/o putting it in the buffer) I'd change it to
scanf("%c\n", &currentGuess);
(note the \n)
The error handling on this is atrocious though. At the least you should check the return value from scanf against 1, and ignore the input (with a warning) if it doesn't return that.
A couple points I noticed:
scanf("%c") will read 1 character and keep the ENTER in the input buffer for next time through the loop
you're incrementing i even when the character read from the user doesn't match the character in secretWord
when does covered[j] ever get to be '-'?
I'll guess: your code is treating a newline as one of the guesses when you enter data. I've always avoided the *scanf() family due to uncontrollable error handling. Try using fgets() instead, then pulling out the first char/byte.
I see a couple of things in your code:
scanf returns the number of items it read. You will probably want to handle the cases where it returns 0 or EOF.
My guess would be that the user is hitting letter + Enter and you're getting the newline as the second character. An easy way to check would be to add a debugging printf statement to show what character was entered.
Your code will only match the first occurrence of a match letter, i.e. if the word was "test" and the user entered 't', your code would only match the first 't', not both. You need to adjust your first loop to handle this.
When you enter the character, you have to enter a whitespace character to move on. This whitespace character is present in the input buffer, stdin file, and is read by the scanf() function.
This problem can be solved by consuming this extra character. This can be done by usnig a getchar() function.
scanf("%c",&currentGuess);
getchar(); // To consume the whitespace character.
I would rather suggest you to avoid using scanf() and instead use getchar(). The scanf()requires a lot of memory space. getchar() is a light function. So you can also use-
char currentGuess;
currentGuess=getchar();
getchar(); // To consume the whitespace character.

Wait for user input in while(1) loop

I'm trying to make a loop in C where the program calculates the avarage of 2 numbers and then waits for user input. If the user input is 'G' then the loop will break. However this is not working currently because it's (in a strange way) a infite loop.
My code is:
while(1){
pogingen++;
gem = (minimum+maximum)/2;
printf("%i",gem);
scanf("%c",&invoer);
if(invoer=='L'){
maximum = gem;
}
if(invoer=='H'){
minimum = gem;
}
if(invoer=='G'){
printf("%i",pogingen);
break;
}
}
I tested it with these values: minimum = 1, maximum = 10. The result will be an infite loop of 5's. It doesn't even wait for the user input (which it's supposed to do.)
Thanks in advance for looking at this!
It doesn't even wait for the user input (which it's supposed to do.).
The program is not waiting to get the input means there is some character left in input buffer. possibly \n from previous input. So clear the input buffer before reading input.
you can put,
getchar();
scanf("%c",&invoer);
before scanf() inside loop;
The reason it doesn't wait for user input in some instances, is because when scanf reads a character, you press the Enter key at the end of the of input, and that key is also stored in the input buffer. So the next iteration it will read that enter key.
This is easily solved by telling scanf to discard trailing whitespace (which the newline character is):
scanf("%c ",&invoer);
/* ^ */
/* | */
/* Notice extra space here */
You might also want to print some error message if the user doesn't give valid input. Also, consider using toupper, because the chances are the user will not give you an upper-case letter.
It might also be better to to use e.g. if ... else if ... else ... instead. Or possibly use a switch statement.
simple and sweet solution invoer=getchar(); that will wait for a character as well as store in to the variable.
no need to write scanf
invoer=getchar();
is a solution if you flush stdin before using it for the next iteration like so:
fflush(stdin);
invoer=getchar();

Scanf skips every other while loop in C

I'm trying to develop a simple text-based hangman game, and the main game loop starts with a prompt to enter a guess at each letter, then goes on to check if the letter is in the word and takes a life off if it isn't. However, when I run the game the prompt comes up twice each time, and the program doesn't wait for the user's input. It also takes off a life (one life if it was the right input, two if it wasn't), so whatever it's taking in isn't the same as the previous input. Here's my game loop, simplified a bit:
while (!finished)
{
printf("Guess the word '%s'\n",covered);
scanf("%c", &currentGuess);
i=0;
while (i<=wordLength)
{
if (i == wordLength)
{
--numLives;
printf("Number of lives: %i\n", numLives);
break;
} else if (currentGuess == secretWord[i]) {
covered[i] = secretWord[i];
secretWord[i] = '*';
break;
}
++i;
}
j=0;
while (j<=wordLength)
{
if (j == (wordLength)) {
finished = 1;
printf("Congratulations! You guessed the word!\n");
break;
} else {
if (covered[j] == '-') {
break;
}
}
++j;
if (numLives == 0) {
finished = 1;
}
}
}
I assume the problem is scanf thinking it's taken something in when it hasn't, but I have no idea why. Does anyone have any idea? I'm using gcc 4.0.1 on Mac OS X 10.5.
When you read keyboard input with scanf(), the input is read after enter is pressed but the newline generated by the enter key is not consumed by the call to scanf(). That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf() call return instantly with no data).
To avoid this, you can modify your code to something like:
scanf("%c%*c", &currentGuess);
The %*c matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call scanf() you are starting with an empty input buffer.
Caveat: If the user presses two keys and then presses enter, scanf() will return the first keystroke, eat the second, and leave the newline for the next input call. Quirks like this are one reason why scanf() and friends are avoided by many programmers.
Newlines.
The first time through the loop, scanf() reads the character.
Then it reads the newline.
Then it reads the next character; repeat.
How to fix?
I seldom use scanf(), but if you use a format string "%.1s", it should skip white space (including newlines) and then read a non-white space character. However, it will be expecting a character array rather than a single character:
char ibuff[2];
while ((scanf("%.1s", ibuff) == 1)
{
...
}
Break the problem up into smaller parts:
int main(void) {
char val;
while (1) {
printf("enter val: ");
scanf("%c", &val);
printf("got: %d\n", val);
}
}
The output here is:
enter val: g
got: 103
enter val: got: 10
Why would scanf give you another '10' in there?
Since we printed the ASCII number for our value, '10' in ASCII is "enter" so scanf must also grab the "enter" key as a character.
Sure enough, looking at your scanf string, you are asking for a single character each time through your loop. Control characters are also considered characters, and will be picked up. For example, you can press "esc" then "enter" in the above loop and get:
enter val: ^[
got: 27
enter val: got: 10
Just a guess, but you are inputting a single character with scanf, but the user must type the guess plus a newline, which is being consumed as a separate guess character.
scanf(" %c", &fooBar);
Notice the space before the %c. This is important, because it matches all preceding whitespace.
Jim and Jonathan have it right.
To get your scanf line to do what you want (consume the newline character w/o putting it in the buffer) I'd change it to
scanf("%c\n", &currentGuess);
(note the \n)
The error handling on this is atrocious though. At the least you should check the return value from scanf against 1, and ignore the input (with a warning) if it doesn't return that.
A couple points I noticed:
scanf("%c") will read 1 character and keep the ENTER in the input buffer for next time through the loop
you're incrementing i even when the character read from the user doesn't match the character in secretWord
when does covered[j] ever get to be '-'?
I'll guess: your code is treating a newline as one of the guesses when you enter data. I've always avoided the *scanf() family due to uncontrollable error handling. Try using fgets() instead, then pulling out the first char/byte.
I see a couple of things in your code:
scanf returns the number of items it read. You will probably want to handle the cases where it returns 0 or EOF.
My guess would be that the user is hitting letter + Enter and you're getting the newline as the second character. An easy way to check would be to add a debugging printf statement to show what character was entered.
Your code will only match the first occurrence of a match letter, i.e. if the word was "test" and the user entered 't', your code would only match the first 't', not both. You need to adjust your first loop to handle this.
When you enter the character, you have to enter a whitespace character to move on. This whitespace character is present in the input buffer, stdin file, and is read by the scanf() function.
This problem can be solved by consuming this extra character. This can be done by usnig a getchar() function.
scanf("%c",&currentGuess);
getchar(); // To consume the whitespace character.
I would rather suggest you to avoid using scanf() and instead use getchar(). The scanf()requires a lot of memory space. getchar() is a light function. So you can also use-
char currentGuess;
currentGuess=getchar();
getchar(); // To consume the whitespace character.

Resources