can someone tell me what's wrong with this code. The value is being stored in 'ch' but if statement is unable to validate it.
scanf(" %c", &ch);
if (ch == 4){
printf("Correct Answer \n");
score++;
}
else{
printf("Wrong Answer \n");
}
%c means you are expecting a character.
So a 4 you input, is not an integer 4, but a character '4'.
Simply check for ch == '4'
Note that char is a numeric type, so this will compile and run, but not do what's expected because we've read a char (with format specifier %c into a char variable ch, but then compare it to the number 4 rather than the character '4'.
You should also get in the habit of checking the return value of scanf as a failure to read into ch if it's uninitialized will lead to unexpected behavior.
if (scanf(" %c", &ch) != 1) {
// Something to handle the error.
}
if (ch == '4') {
printf("Correct Answer \n");
score++;
}
else {
printf("Wrong Answer \n");
}
Related
This question already has answers here:
problem in scanning character in C
(8 answers)
Closed 1 year ago.
int main()
{
char Operator;
int num1, num2, result;
/* printf("Enter operator: ");
scanf("%c", &Operator);*/
printf("Enter first and second value: ");
scanf("%d %d", &num1, &num2);
printf("Enter operator: ");
scanf("%c", &Operator);
if(Operator == '+')
{
result = num1 + num2;
printf("%d\n", result);
}
else if(Operator == '-')
{
result = num1 - num2;
printf("%d\n", result);
}
return 0;
}
I tried making a simple calculator, and I put scanf(the one that requests an Operator) where it is now, and it does not work. But if I put it where the comment is, above the "Enter first and second value" it then works. I would just like to know why does it work on one place and not the other.
Thanks in advance.
As pointed out in comments, Your first scanf is reading the integer values but it's not reading the newline in buffer. When you do scanf("%c", &Operator) again for taking character input, it reads that newline character still present in input buffer. To avoid this, you can use scanf(" %c", %Operator) instead which will discard all whitespace characters before matching character:
printf("Enter operator: ");
scanf(" %c", &Operator);
You can also use fgets() to read input into a string and then use sscanf() to read integers from string:
char input[100];
printf("Enter first and second value: ");
if (fgets(input, 100, stdin) == NULL) {
printf("No input provided!\n");
return -1;
}
if (strchr(input, '\n') == NULL) {
printf("Input Buffer Overflow\n");
return -1;
}
if (sscanf(input, "%d %d", &num1, &num2) != 2) {
printf("Error in reading characters\n");
return -1;
}
printf("Enter operator: ");
if (fgets(input, 100, stdin) == NULL) {
printf("No input provided!\n");
return -1;
}
if (strchr(input, '\n') == NULL) {
printf("Input Buffer Overflow\n");
return -1;
}
if (sscanf(input, "%c", &Operator) != 1) {
printf("Error in reading characters\n");
return -1;
}
From the Open Group Base Specifications Issue,
Input white-space characters (as specified by isspace()) shall be
skipped, unless the conversion specification includes a [, c, C, or n
conversion specifier.
%d format specifier will skip preceding input newline character (\n). That's why it works in the first case (case, where operator was read first) .
scanf leaves an newline character \n in the input buffer, after the first scanf.
The second scanf will read the extra \n from the input buffer to variable Operator. That's why it will not work.
Since the format specifier is %c, the newline character will not be skipped.
Solution : Use scanf(" %c", &Operator);. Add an extra space at the beginning.
I'm creating a conversion project for letters/numbers ASCII table. My code is supposed to be 'interactive', so the user would type 'y' or 'n' to answer questions on the screen. However, it doesn't want to do this twice...
I have tried:
Just trying numbers instead of characters, but it's not exactly what I want
The %[\n]*c, and %[\n]c, and %[\n]*s ... technique but it doesn't help ;-;
Testing in a different project, but the only way I am able to do it is for multiple scanf()s to be in a row.
Here is the code:
printf("Would you like to convert a number today? \n");
printf("Please press Y or N \n");
scanf("%c", &input);
if (input == 'y' || input == 'Y') { //compare input if they said 'yes'
printf("\nThank you! \nWhat number?\n");
scanf("%d", &number);
flag = test(number);
if (flag == 0) { //if there is an equivalent letter
letter = conversion(number); //find the equivalent letter
printf("\nYour Number \t ASCII letter\n");
printf("%d\t %c\n", number, letter);
}
}
else if (input == 'n' || input == 'N') {
printf("\nWould you like to convert a letter instead? This time enter 0 or 1\!\n\n"); //problem here!!
printf("I wish I could say it was to \' Spice things up \' ...but it\'s not ;-; \n\n");
scanf("%d", &input2);
if (input2 == 0) { //this needs to be checking whether the user input Y/y
printf("Great choice adventurer!\n");
printf("What letter will it be today?\n\n");
//..I would go to a different funtion here ie: test2(letter)...
scanf("%d", &number); //I showed that it worked with multiple numbers, but I can't get this to work with multiple letters
printf("%d", number);
}
if (input2 == 1) { //this needs to be checking whether the user input N/n
printf("Difficult to please, I see...\n\n");
printf("I suggest you move on with that attitude!\n\n");
printf("Bye bye then\n");
}
}
else { //if they tried to break the code
printf("Sorry I did not recognise your command...please retry\n");
printf("Press Y or N next time!\n");
}
The first check works perfectly, I just want the second check to be like the first!
Some 'solutions' caused a overflow, which I don't want if possible
Even if someone could explain why this isn't working the way I intended would be very helpful!
I'm not sure what confuses you.
Use
char foo;
scanf(" %c", &foo);
for single characters, eg. letters and
int bar;
scanf("%d", &bar);
for numbers, integers. If you type a letter instead, scanf() will fail.
%[...] is for strings.
scanf() returns the number of successful conversions (or EOF), so for
int height;
int width;
scanf("%d %d", &height, &width);
it returns 2 if successful. It might return 1 if only height could be read.
So to check for errors on user input you should do:
int height;
int width;
if (scanf("%d %d", &height, &width) != 2) {
// handle the error, maybe exit the program.
}
Your code could look like that (without error handling):
#define _CRT_SECURE_NO_WARNINGS // you said Visual Studio? Without it you should get
// warnings about some functions being insecure.
#include <ctype.h> // isalpha() returns true if the value is a letter
#include <stdlib.h> // EXIT_SUCCESS
#include <stdio.h> // puts(), printf(), scanf()
int main(void)
{
for(;;) { // for-ever ... endless loop since the user exits by answering
// 'n' or 'N' two times
puts("Would you like to convert a number today?\nPlease press Y or N:");
char input;
if (scanf(" %c", &input) != 1) // We reached EOF ... end of file
break; // that's improbable for stdin,
// but input could be redirected to
// read from a file instead.
if (input == 'y' || input == 'Y') {
puts("\nThank you!\nWhat number?");
int number;
scanf("%d", &number);
if (isalpha((char unsigned)number)) // *)
printf("\nYour Number \t ASCII letter\n%d\t %c\n\n", number, number);
else
puts("Sorry, but that's not the ASCII code of a letter :(\n");
}
else if (input == 'n' || input == 'N') {
puts("\nWould you like to convert a letter instead?\nPlease press Y or N:");
scanf(" %c", &input);
if (input == 'y' || input == 'Y') {
puts("\nGreat choice adventurer!\nWhat letter will it be today?");
char letter;
scanf(" %c", &letter);
if (isalpha(letter))
printf("\nYour letter \t ASCII code\n%d\t %c\n\n", letter, letter);
else
puts("Sorry, but that's not a letter :(\n");
}
else if (input == 'n' || input == 'N') {
puts("\nDifficult to please, I see...\n\nI suggest you move on with that attitude!\n");
puts("Bye bye then.");
return EXIT_SUCCESS;
}
}
else {
puts("Sorry I did not recognize your command... Please retry.");
puts("Press Y or N next time!\n");
}
}
}
*) isalpha() (and the other functions in <ctype.h>) expects a value that fits in a unsigned char or the value EOF. It has undefined behaviour for other values. Since we read user input into an int we cannot be sure that's the case so we have to cast the value to unsigned char before passing it to isalpha() (and friends).
Next time you ask a question please include your full code, including variable declarations, functions like test() and conversion() and #includes. But please, post an example that focuses on your problem at hand. All that dialog you included would not have been necessary.
#include <stdio.h>
int main()
{
char ch;
int i;
for (i = 1; i <= 5; i++) {
printf("Enter a Character: ");
scanf("%s", &ch);
if ((ch >= '0') && (ch <= '9'))
printf("The character is a numeral\n");
else if ((ch >= 'A') && (ch <= 'Z'))
printf("The character is in upper case\n");
else if ((ch >= 'a') && (ch <= 'z'))
printf("The character is in lower case\n");
else
printf("The character is a special character\n");
}
return 0;
}
I want to read a character input from user and display the character type. However everytime after running the last scan of the program, it will have a debug error. I am using Visual Studios C++ 2010 Express.
Run-Time Check Failure #2 - Stack around the variable 'ch' was corrupted.
Please help!
To scan a char use
scanf("%c", &ch);
Using wrong format specifier will lead to undefined behavior.
Please make sure you ignore the newline char and do it by placing a space before %c
scanf(" %c", &ch);
The space before the %c will make sure that the newline char in the buffer gets ignored. i.e space gobbles the newline char.
In scanf,
If you want to the single character you have to use the control string %c. %s for
getting the string.
So change the scanf into
scanf(" %c", &ch);
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.
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 6 years ago.
I thought of making a calculator, just a simple one with loops and the basic operations, but the weird thing is that the scanf of character in between my scanf for number is being ignored. It works fine if I put it on top of the scanf of integer but it wouldn't look anything like a calculator. Is there any way to solve this issue? It's not yet finished; got an error up to here, so wondering what's wrong.
#include <stdio.h>
#include <stdlib.h>
int main(){
int number1,number2,total;
char a;
printf("This is your personal calculator:(End with ""="")\n");
scanf("%d",&number1);
scanf("%c",&a);
scanf("%d",&number2);
if (a == 'x' || a == 'X' || a == '*'){
total=number1*number2;
printf("%d",total);
} else if (a == '/'){
total=number1/number2;
printf("%d",total);
} else if (a == '+'){
total=number1+number2;
printf("%d",total);
} else if (a == '-'){
total=number1-number2;
printf("%d",total);
} else {
printf("error");
}
system("pause");
return 0;
}
You should test that you get a value from scanf(), every time.
The %c character reads the blank or newline after the first number; use " %c" with a leading space to skip over optional white space before reading the character.
if (scanf("%d", &number1) == 1 &&
scanf(" %c", &a) == 1 &&
scanf("%d", &number2) == 1)
{
...process possibly valid input...
}
else
{
...diagnostics...
}
It will probably be easier to give good diagnostics if you read whole lines with fgets() and parse them with sscanf().
Recommendation 1: show an example of what you type as input and what you get as output. This makes it easier for people to help you (they can tell whether the program is producing the same output for them).
Recommendation 2: echo your input so you can see what the program got. This allows you to tell whether the program got the input you expected. You'd probably find that number2 was not containing what you expected, for example.
Recommendation 3: initialize number1 and number2 to -1 so you can see when the scanf() failed (since you aren't yet checking whether scanf() succeeded).
The problem is because of the newline char \n left over by the scanf. This could be avoided by placing a space before format specifier %c.
Try this
scanf(" %c", &a);
^ An space
this will help you to eat up \n char left over by first scanf
int main()
{
int number1,number2,total;
char a;
printf("This is your personal calculator:(End with ""="")\n");
scanf("%d",&number1);
fflush(stdin); // SIMPLE WAY FLUSH THE INPUT STREAM, INPUT BUFFER IS USUALLY CLEARED.
scanf("%c",&a);
scanf("%d",&number2);
if (a == 'x' || a == 'X' || a == '*'){
total=number1*number2;
printf("%d",total);
} else if (a == '/'){
total=number1/number2;
printf("%d",total);
} else if (a == '+'){
total=number1+number2;
printf("%d",total);
} else if (a == '-'){
total=number1-number2;
printf("%d",total);
} else {
printf("error");
}
system("pause");
return 0;
}