This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 4 years ago.
I wrote this code for a school project and I have the following problem.
When I choose 1 at the first time, my program runs fine but as I choose w or r the second time, something goes wrong. None of the 2 ifs is running. I printed usr_ans2 to see the result of scanf and usr_ans2 variable is a weird question mark in a box and not a w or r character as I typed. Also I tried scanf(" %c", usr_ans2) . The question marks do not appear but the if commands are still not running.
int main(){
int usr_ans1;
char usr_ans2;
while(1){
printf("\nSelect action: (1-3)\n");
scanf("%d", &usr_ans1);
if(usr_ans1 == 1){
printf("Select to write or read from a file the text: (w/r) ");
usr_ans2 = scanf("%c", &usr_ans2);
if(usr_ans2 == 'w')
printf("You selected to write");
else if(usr_ans2 == 'r')
printf("You selected to read");
}
else if(usr_ans1 == 2){
printf("Example1");
}
else if(usr_ans1 == 3){
printf("Example2");
}
return 0;
}
scanf() in usr_ans2 = scanf("%c", &usr_ans2); will return 1 (the numbers of successfully converted specifiers) or EOF (some negative value like -1 when end-of-file or error occurs). if(usr_ans2 == 'w') will never be true.
Try
// usr_ans2 = scanf("%c", &usr_ans2);
scanf(" %c", &usr_ans2); // add the space too to skip leading white-space
Related
This question already has answers here:
How to scanf only integer?
(9 answers)
Closed 4 years ago.
I want to know how to keep taking inputs from keyboard with this condition: If the given input is a positive number, it keeps going with the code If the given input is a negative number or a letter, it must print "insert a positive number" and then ask again for another input until it has the correct one. About negative and positive inputs the code i wrote works great, but it bugs out when I put a letter. The check I tried is the following
chk=isalpha(n);
while(!chk || n<0)
{
printf("Inserire un intero positivo \n");
scanf("%d", &n);
chk=isalpha(n);
}
printf("%d\n%d\n", t1, t2);
In this case if I put a negative number it works correctly, but if I type a letter the printf loops. I also tried while(isalpha(n) || n<0) And a bunch of other pieces of code I'll skip for you. Please help me figure this out
You can check return value of scanf in case of char it returns 0 along with that you need to clear the buffer to stop scanf consuming the same character.
Example:
int ret = 0;
do
{
char c;
while ((c = getchar()) != '\n' && c != EOF) { } /* to clear the bad characters*/
printf("Inserire un intero positivo \n");
ret = scanf("%d", &n);
}while(!ret || n<0);
This question already has answers here:
The program doesn't stop on scanf("%c", &ch) line, why? [duplicate]
(2 answers)
Closed 6 years ago.
I'm an absolute beginner to coding in C and I'm attempting to practice by writing a program where a user responds to Yes/No questions in a series, like if it were a game.
The problem that I'm having is that after the first question is answered, and the second pops up, the program doesn't give me (the user) a chance to respond to it; the program abruptly ends.
Obviously, there must be something simple that I'm missing here to go from one question to another without it terminating. I'd appreciate any advice.
Here's what I've made so far:
#include <stdio.h>
char answer, answertwo;
int main()
{
printf ("Are you laughing? (Y/N)\n" );
scanf ("%c", &answer);
if (answer == 'y' || answer == 'Y')
printf("\nGood\n");
else if (answer == 'n' || answer == 'N')
printf("\nBye\n");
printf("Do you want to read? (Y/N)\n ");
scanf ("%c, &answertwo");
if (answertwo == 'y' || answertwo == 'Y')
printf("\nGood\n");
else if (answertwo == 'n' || answertwo == 'N')
printf("\nBye\n");
return 0;
}
Two things:
You have a typo on the line scanf ("%c, &answertwo");, move the quote to the end of the first argument:
scanf ("%c", &answertwo);
The second call to scanf ends prematurely because it consumes the newline in stdin from the first call. Try replacing your format specifiers in scanf from "%c" to " %c" so that they will ignore whitespace before the actual character is input.
This question already has answers here:
Why is my c != 'o' || c != 'x' condition always true? [duplicate]
(5 answers)
Closed 6 years ago.
Does anybody have any idea why this always loops for values different than 1 or 0,and also how can i avoid the endless loop in case of giving a character as input?
#include <stdio.h>
int a;
main()
{
do
{
puts("Give 1 or 0 for input:");
scanf("%d",&a);
} while(a!=0 || a!=1);
printf("\n%d",a);
return 0;
}
The only way for the loop to terminate is if both a!=0 and a!=1 are false. Or in other words: it can only end when a == 0 and a == 1 at the same time. That is of course impossible, so the loop never terminates.
If you want to loop to terminate when the user inputs 1 or 0, then you need a logical and operator there:
do
{
puts("Give 1 or 0 for input:");
scanf("%d",&a);
} while(a!=0 && a!=1);
Aside from that, you really must check the return value of scanf, and purge the input stream in case of failure. If you input a character, then scanf will signify it failed, but leave the character in the input stream. The subsequent iterations will just get stuck on trying to read that character.
One way to do so is with scanf itself and the %*s format specifier.
do
{
puts("Give 1 or 0 for input:");
int read_res = scanf(" %d",&a);
if (read_res != 1)
scanf("%*s");
} while(a != 0 && a != 1);
The asterisk in the format string means scanf will still match any non white-space character and purge them from the stream, but will not attempt to assign them into anything (so no extra parameter is required). I also added a leading white-space to %d in order to disregard any leading white-spaces before the number.
This question already has answers here:
How to check if input is numeric in C++
(8 answers)
Closed 7 years ago.
This is what I have now:
int main() {
int number;
printf("Type your number: ");
scanf("%i",&number);
char code[4];
printf("Type your code: ");
scanf("%s",&code);
When I type anything but numbers in the first one the script goes all crazy, it just shows
Type your number: NOTaNUMBER
Type your code: THErestOFtheSCRIPT
-- Back to command line
What I want it to do is
Type your number: NOTaNUMBER
You didn't enter a number
-- Back to command line
How can I do this?
This is different from the said duplicate. I'm talking about C here, not C++.
C doesn't know cin, the answer to the said duplicate. However, an answer was found below
For input string use
scanf("%s",code);
or better
scanf("%3s",code);
To check correct input for number use value returned by scanf:
char ch;
if( 1 == scanf("%i",&number) )
{
// use correct number
}
else
{
// clean input bufer
while( (ch = getchar()) != '\n' && ch != EOF);
}
This question already has answers here:
C programming: character in scanf [duplicate]
(2 answers)
Closed 8 years ago.
I have the following code, i wanted to terminate the while loop if any key except 1 & 2 is press. but only do executes once. and not while. why my while condition is always false. please guide:
char a;
do
{
printf("To Enter the Employee sales press 1 \n");
printf("To Add more items press 2 \n ");
printf("Press any key to Terminate \n\n");
scanf("%c", &a);
if ( a == '1' )
{
printf("1 is presed ");
}
else if(a == '2')
{
int c;
printf("entre Value:");
scanf("%d",&c);
printf("\n");
addItem( &myArray, &size, c );
printitems(myArray, size);
}
}while(a == '1' || a == '2');
Edit So sorry, it was in single qout. i forgot to put the latest code. Even with qoutes it does not run while.
You need a space before your %c in scanf():
scanf(" %c", &a);
You're reading the first character that's entered and leaving one on the buffer. So if you enter:
'1' you're really getting two characters, first '1' then a '\n' (a "1" then a new line character, that happens when you hit enter). So it first stores '1' into a, then the second time it will read the remaining newline character into a, (it will apear to "skip" asking you for input). Since '\n' is not equal to '1' or '2' so it correctly exits.
Adding the space before the %c tells scanf() to ignore any white space left on the buffer (and new line characters count as white space)
You have declared 'a' as type char. and your while condition is
while(a == 1 || a == 2);
It should be
while(a == '1' || a == '2');