Program is not looping - c

I am trying to make the program print out "OK" for as long as i enter 'y' as a choice at the end, but it is not looping, it just prints out "OK" and ends the program even if i enter a 'y' at the end. Please help.
#include <stdio.h>
int main()
{
char c = 'y';
while (c == 'y')
{
printf_s("OK\n");
scanf_s("%c", &c);
if (c != 'y')
{
break;
}
}
return 0;
}

On first iteration when you press Enter key then a newline character \n is passed to the input along with y. On second iteration scanf_s reads \n.
Change
scanf_s("%c", &c);
to
scanf_s(" %c", &c);
^Notice the space before %c
A space before %c specifier can consume any number of white-space characters.

Change the scanf_s line as follows
scanf_s("%c", &c, 1);
This extra parameter is specifying the size of the c argument. Plain old scanf doesn't require this argument but the versions ending with _s do
Also the if block with the break statement is unnecessary because the conditional on the while loop effectively does the same thing. It could be written as follows
while (c == 'y')
{
printf_s("OK\n");
scanf_s("%c", &c, 1);
}

OK I used scanf instead of scanf_s, that solved the problem, thanks everyone.

You are wrong with scanf
if you use like this u will see it is working ..
#include <stdio.h>
int main()
{
int c = 1;
while (c == 1)
{
printf_s("OK\n");
scanf_s("%d", &c);
if (c != 1)
{
printf_s("hello\n");
continue;
}
}
return 0;
}

Put a space before %c to skip whitespace.

Related

Scanf function skips

In similar questions, the scanf reading a char or string skips because it takes in a new line from the input buffer after the "Enter" key is pressed for the previous scanf, but I don't think that's the issue here. This program does not skip the 2nd scanf if input1 is an integer, but it skips it for other types of inputs (double, char, string, etc.).
#include <stdio.h>
#include <string.h>
int main(){
int input1;
char input2[6];
printf("Enter an integer. ");
scanf("%d", &input1);
printf("You chose %d\n", input1);
printf("Write the word 'hello' ");
scanf(" %s", input2);
if (strcmp(input2,"hello")==0){
printf("You wrote the word hello.\n");
} else {
printf("You did not write the word hello.\n");
}
return 0;
}
Why does this happen?
Comments in code:
int input1 = 0; // Always initialize the var, just in case user enter EOF
// (CTRL+D on unix) (CTRL + Z on Windows)
while (1) // Loop while invalid input
{
printf("Enter an integer. ");
int res = scanf("%d", &input1);
if ((res == 1) || (res == EOF))
{
break; // Correct input or aborted via EOF
}
int c;
// Flush stdin on invalid input
while ((c = getchar()) != '\n' && c != EOF);
}
printf("You chose %d\n", input1);
Also, take a look to How to avoid buffer overflow using scanf
Did you try to write "%*c" after your %c or %s or %d ?
Something like this : scanf("%s%*c", input1);

scanf formatted input does not apply to first character scanned

I'm trying to write a program that outputs non-vowel characters (without if statements and using formatted scanf input). The code I currently have does not apply the %*[] ignored characters to the first %c character scanned, but the restriction applies for the other characters. For example, "Andrew" becomes "Andrw" instead of "ndrw". I'm suspecting this could be due to the %c at the beginning. Could someone help me please? :)
#include <stdio.h>
#include <string.h>
int main(void) {
char c;
while (scanf("%c%*[aeiouAEIOU]", &c) == 1)
printf("%c", c);
return 0;
}
The scanf formats are matched in order so %c is matched first for the A. You need to use 2 separate scanfs for this, or precede the loop with the initial-vowel eating scanf:
scanf("%*[aeiouAEIOU]");
while (scanf("%c%*[aeiouAEIOU]", &c) == 1) {
printf("%c", c);
}
The question is is this any clearer and better than
int c;
while ((c = getchar()) != EOF) {
if (! strchr("aeiouAEIOU", c)) {
putchar(c);
}
}
I have an opinionated answer...

Program looping two times (printing statement twice)

I'm trying to make a simple program for which the user is supposed to enter character 'a'. It is supposed to loop until 'a' is input. I have one statement printed if there is no input which works correctly. There is another statement if an incorrect letter or number is input, but the problem is that this causes the program to loop more than once and it prints the statements multiple times. Any help in fixing this is appreciated.
#include <stdio.h>
int main()
{
char input;
int i, len,num;
len = 1;
do
{
puts("Please enter alphabet 'a': ");
scanf("%c", &input);
for(i=0; i<len; i++)
{
if(isalpha(input)==0)
{
printf("Please input something.\n");
continue;
}
if(input == 'A' || input == 'a')
{
printf("Congratulations! You successfully input letter 'a'.");
return(0);
}
else
{
printf("That's not letter 'a'.");
}
}
}
while(1);
}
The problem is that after entering the character, you press newline and this is send to the input buffer. Now the next time scanf() is called, it reads the value from the buffer which is '\n' and scanf() thus stores this to input. Now this can be easily solved by the method pointed by #Gopi, but there is a better way. This is the code.
#include <stdio.h>
#include<ctype.h>
int main()
{
char input,ch;
do
{
puts("Please enter alphabet 'a': ");
scanf("%c", &input);
while( input!='\n' && (ch=getchar())!='\n' && ch!= EOF); // look here
if(isalpha(input)==0)
{
printf("Please input something.\n");
continue;
}
if(input == 'A' || input == 'a')
{
printf("Congratulations! You successfully input letter 'a'.");
return(0);
}
else
{
printf("That's not letter 'a'.");
}
}
while(1);
}
Now with the statement while((ch=getchar())!='\n' && ch!= EOF);, all the characters like '\n' are just flushed and not stored to input and thus solves the problem.
Also note that you don't need the for loop here, its useless for this code ( unless this is not your original code and there are other parts in it ).
There is a newline character in the buffer after the first input which is not flushed and that is being picked up by the %c in the second iteration.
Change your scanf() to
scanf(" %c", &input);
Note the space before %c which gobbles the newline character

input a letter, store in a variable print the letter to the command line

I am trying to make a very basic program to compare 2 numbers. after entering the 2 numbers the user is asked if they want to compare the 2 numbers. if y/n for yes or no. the problem I run into is that the program does not seem to ask for my input and immediately goes to the next print statement. Here is the code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(void){
int n1;
int n2;
char ch;
printf("compare 2 numbers, input a number\n");
scanf("%d", &n1);
printf("your first number is %d\n", n1);
printf("enter your second number to compare \n");
scanf("%d", &n2);
printf("your second number is %d\n", n2);
printf("do you want to compare these numbers? y/n \n");
//here is the problem. after entering y, the program closes.
//at this point I just want it to print the letter it was given by the user.
scanf("%c", &ch);
//the print statement that is supposed to print the letter the user inputs
printf("%c is a vowel.\n", ch);
getch();
return 0;
}
//I was using this code as a reference which runs correctly
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I'
|| ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
printf("%c is a vowel.\n", ch);
else
printf("%c is not a vowel.\n", ch);
return 0;
}
When you do
printf("enter your second number to compare \n");
scanf("%d", &n2);
you will enter the second number and press ENTER. This ENTER (\n) is still there in the buffer.
The scanf function removes whitespace automatically. scanf() leaves the new line char in buffer when you are using %c (%c are the exception they don't remove whitespace).
scanf("%c", &ch);
instead of this use
scanf("\n%c", &ch);
When you use %c,spaces and "escape character" as a valid character.So it will be stored in the ch.In the first two scanf,you use the %d can do no wrong.
In the second program,you call scanf("%c", &ch); at the first.This problem does not arise.If you call again, also can appear the same problem.
The reason for this problem is newline character \n leftover by the previous scanf after pressing Enter. This \n is left for the next call of scanf.
To avoid this problem you need to place a space before %c specifier in your scanf.
scanf(" %c", &C);
...
scanf(" %c", &B);
...
scanf(" %c", &X);
A space before %c is able to eat up any number of newline characters.
OR
You can use scanf to eat the single character without assigning it to anything like this::
scanf( "%[^\n]%*c", &C ) ;
%[^\n] tells the scanf to read every character that is not '\n'. That leaves the '\n' character in the input buffer, then the * (assignment suppression) will consume the a single character ('\n') but would not assign it to anything.

Reading character with scanf()

This code is for game of craps.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int roll_dice(void);
bool play_game(void);
int main()
{
int i, ch,win = 0,lose = 0;
bool flag;
srand((unsigned)time(NULL));
do
{
flag = play_game();
if(flag)
{
printf("You win!");
win++;
}
else
{
printf("You lose!");
lose++;
}
printf("\n\nPlay again(Y/N)? ");
scanf("%c", &ch);
ch = getchar();
printf("\n");
}while(ch == 'Y' || ch == 'y');
printf("\nWins: %d Losses: %d",win,lose);
return 0;
}
int roll_dice(void)
{
return rand()%6 + rand()%6 + 2;
}
bool play_game(void)
{
int sum = roll_dice();
printf("You rolled: %d\n", sum);
if(sum == 7 || sum == 11)
return 1;
else if(sum == 2 || sum == 3 || sum == 12)
return 0;
else
{
int point = sum;
printf("Your point is: %d\n", point);
do
{
sum = roll_dice();
printf("You rolled: %d\n", sum);
if(sum == 7)
return 0;
}while(point != sum);
return 1;
}
}
I have problem only with code snippet
printf("\n\nPlay again(Y/N)? ");
scanf("%c", &ch);
ch = getchar();
printf("\n");
I have used, because it terminates after one iteration whatever user input Y or N. I thought I am doing wrong by placing ch = getchar() to eat up \n, I removed it and placed a space before conversion specifier and replaced it by " %c" which also did't work.When I replaced the conversion specifier by %d it works fine.
Is anything going wrong with this?
I visited this post and it is saying same thing I did.
The posted code has undefined behaviour because ch is of type int and the format specifier %c must match a char.
When I replaced the conversion specifier %d it works fine.
When you switch to %d the scanf() fails, because Y or y is not an int, so no input is consumed (apart from leading whitespace which discards the new line character on subsequent iterations of the loop) and the subsequent ch = getchar() actually reads the user entered character, and the code works by fluke. Always check the return value of scanf(), which returns the number of assignments made.
You convert the character with scanf(), and then overwrite it with getchar() immediately afterwards. I wouldn't expect it to work, unless you type "yy" before typing ENTER, but then your second confirmation would fail.
BTW, use the space in " %c".
scanf("%c", &ch);
ch = getchar();
And that's how you lost the previous char stored in ch. How about
ch = fgetc(stdin);
while (fgetc(stdin) != '\n')
;
instead?
printf("Play again? ");
scanf(" %c", &char);
this code works for me. The project is from K.N.King's "C programming : A modern approach" book. I met with this problem before and had the same problem. On page 224 there is a guess.c example project which includes exactly the same command "ask" ("play again"). And author used scanf(" %c", &command); (he used command instead of ch) and it did work. I remember I used it during the "game of craps" project but it did not work. Probably I missed something.
Overall, the expression above 100% does work.

Resources