Can someone solve this Code Blocks? - c

Solve this for me because I don't really know
#include <stdio.h>
#include <stdlib.h>
int main() {
char ans;
printf("1. The patients felt _____ after taking the medicine.\n");
printf("\t a. best\n\t b. better\n\t c. good\n\n");
scanf("%c", &ans);
if (ans == 'b') {
printf("2. I ______ my essay by the time the bell rings.\n");
printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
scanf("%c", &ans);
} else {
printf("YOU FAILED!");
};
return 0;
}
If you answer the first question you proceed to next and answer the 2nd question, but the problem is I can't type the answer even though there's scanf.

#include <stdio.h>
#include <stdlib.h>
int main() {
char ans;
printf("1. The patients felt _____ after taking the medicine.\n");
printf("\t a. best\n\t b. better\n\t c. good\n\n");
scanf("%c", &ans);
if (ans == 'b') {
printf("2. I ______ my essay by the time the bell rings.\n");
printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
scanf(" %c", &ans);
} else {
printf("YOU FAILED!");
};
return 0;
}
The difference is:
scanf(" %c",&ans);
^ this space this will read whitespace characters (which newline also is)
until it finds a non space character.
scanf did not consume the \n character that stayed in the buffer from the first scanf call.
I try this, and it works!

The second scanf("%c"...) reads the linefeed that the first scanf left pending in standard input. You can fix this by reading an extra character this way:
#include <stdio.h>
#include <stdlib.h>
int main() {
char ans;
printf("1. The patients felt _____ after taking the medicine.\n");
printf("\t a. best\n\t b. better\n\t c. good\n\n");
scanf("%c%*c", &ans);
if (ans == 'b') {
printf("2. I ______ my essay by the time the bell rings.\n");
printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
scanf("%c%*c", &ans);
} else {
printf("YOU FAILED!");
}
return 0;
}
scanf("%c%*c", &ans) reads a character and stores it into the ans variable, then it reads another character and discards it. This way the \n typed by the user after the b is discarded.
An alternative is to ignore white space characters with scanf(" %c", &ans): the in the scanf format instructs scanf to read and ignore any whitespace characters. The advantage of the first approach is that no characters are left pending after the scanf if the user entered a single character followed by enter, the second approach would leave the \n pending, but it would be ignored by the following scanf.

Related

C program, getting the integer value of a character. Why everything comes out after line 10?

Hi I am new to programming and I got a trouble when I try to make a little change to the example in the book.
/* Chapter 3 Example, C Prime Plus */
#include <stdio.h>
int main(void)
{
char Letter, ch;
int intValue;
printf("Please enter a letter: \n");
scanf("%c", &Letter); /* user inputs character */
printf("The code for %c is %d.\n", Letter, Letter);
printf("Now is another we to implement the process: \n");
printf("RN, the value of ch is %c, and the value of intValue is %d\n", ch, intValue);
printf("Please enter a letter: \n");
scanf("%c", &ch);
intValue = ch;
printf("The code for %c is %d.\n", ch, intValue);
return 0;
}
When I run it, the outcome would be
Please enter a letter:
M
The code for M is 77.
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10.
and the part
"
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10. " will all come out without asking me to enter a value.
I want to know why and are there any other way to implement it that is different from examples in the book?
Thank you for your time!
Hi Matt_C and welcome to SO.
First, you don't need the second bloc of printfs and the scanf, it just trying to do the same thing and there is an order error.
Second, it is tricky when you try consecutive scanf, it holds the last key pressed (enter is the last key pressed = \n). This is why it skips the second scanf.
There a little solution for that, add a space at the beginning of the scanfs. Try this:
int main() {
char exit, letter;
while (1) {
printf("Please enter a letter: ");
scanf(" %c", &letter);
printf("\nThe code for '%c' is %d. \n\n", letter, letter);
printf("Exit ? (y/n): ");
scanf(" %c", &exit);
if(exit == 'y')
{
break;
}
system("clear"); // UNIX
//system("cls"); // DOS
}
}
Don't forget to choose one answer that you believe is the best solution to your problem.

Why procedure if in C doesn't work with char

I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,

How to Make this Code Work (isdigit) [duplicate]

This question already has answers here:
Check if input is float else stop
(6 answers)
Closed 7 years ago.
So, I'm creating a program that calculates the area of a triangle, and I need it to tell the user if he typed a letter or a negative number, in order, I created the code:
I need to use isdigit
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A.");
fflush(stdin);
scanf("%f",&a);
while(a<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&a);
}printf("Inform the value of side B.");
fflush(stdin);
scanf("%f",&b);
while(b<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&b);
}printf("Inform the value of side C.");
fflush(stdin);
scanf("%f",&c);
while(c<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&c);}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f",s);
printf("The area of the triangle is%f",ar2);
system ("pause");
return 1;
}
But, when I compile/run it, and type "x", or "blabla" when I was supposed to type a number, nothing happens, and the program doesn't warn me, what should I do?
First of all, using fflush on stdin is Undefined Behavior as per the C11 standard, although it is well defined on some implementations.
Secondly, you can't use simply use isdigit that way. Once %f sees invalid data such as characters, the scanf terminates and the corresponding argument is left untouched. Also, using isdigit on an uninitialized variable leads to Undefined Behavior.
What you can do is check the return value of scanf. All the three scanfs in your code returns 1 if successful.
Fixed Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h> //Unused header
void flushstdin() //Removes all characters from stdin
{
int c;
while((c = getchar()) != '\n' && c != EOF); //Scan and discard everything until a newline character or EOF
}
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A\n");
//fflush(stdin); Avoid this to make your code portable
while(scanf("%f",&a) != 1 || a <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side B\n");
//fflush(stdin);
while(scanf("%f",&b) != 1 || b <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side C\n");
//fflush(stdin);
while(scanf("%f",&c) != 1 || c <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f\n", s);
printf("The area of the triangle is %f\n", ar2);
system ("pause");
return 0; // 0 is usually returned for successful termination
}
Also, it is better to add newline characters at the end of the strings in printf as seen in the above program. They
Improve readability
Flushes the stdout

My program skip getting input data? [duplicate]

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 9 years ago.
I have written a simple program to exchange currency and able to buy a beer.
But there something in program and I don't know why, it auto skips the third input data -> end program.
Here my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ex_rate_into_vnd = 20000; //! Exchange Rate
int beer = 7000; //! Local price of a beer
float in_c = 0; //! Input amount of money
float out_c = 2; //! Amount of currency to exchange !
float choice; //! Switch mode
char buy; //! Deal or not
//! Introduction
printf ("||---------------------------------------------------||\n");
printf ("|| Currency Exchange Machine beta ||\n");
printf ("||---------------------------------------------------||\n");
printf ("Please choose your option:\n");
printf("\t 1.Exchange VND to dollar\n");
printf("\t 2.Exchange Dollar to VND\n");
do
{
printf("Your choice: ",choice);
scanf("%f",&choice);
} while( choice != 1 && choice != 2);
printf ("Please enter amount of money:");
scanf("%f",&in_c);
if (choice == 1 )
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
else
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
//! End of Exchanging
printf ("\nWould you like to buy a beer (y/n) ?",buy);
scanf("%c", &buy);
if (buy == 'y')
{
if (out_c >= 7000)
{
out_c = out_c - 7000;
printf("Transactions success !\n");
printf("Your amount: %2.f",out_c);
}
}
printf ("\nWhy Stop ?");
return 0;
}
You have at least one \n between the latest float entry and the char you want to read. You need to get rid of that first.
See also all answers in getchar after scanf category
Change
scanf("%c", &buy);
to
scanf(" %c", &buy);
// ^space
Because the newline character is still in the input buffer after you enter a number and press ENTER in the second scanf.
Instead of scanf("%c", &buy);
1.use space before %c
scanf(" %c",&buy); //space before %c
^
this skips reading of white space (including newlines).
2.or Use getchar(); before scanf("%c", &buy); statement
getchar(); //this hold the newline
scanf("%c", &buy);
3.or use two times getchar();
getchar();
buy=getchar();
//here getchar returns int , it would be better if you declare buy with integer type.
In GCC usage of fflush(stdin); is discouaraged. please avoid using it.
I was wondering why you made 'choice' a float, not an int
Also, consider using a switch-case
that way, you won't have to do the whole do-while loop.
Also, in the line
printf ("\nWould you like to buy a beer (y/n) ?",buy);
Why did u add that?
Here is what I would have done :
printf("Your choice?\n>");
scanf("%d", &choice);
switch(choice)
{
case 1 :
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
case 2:
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
default :
printf("\nThere has been an error\n"):
reloadprogram(); /* Reloadprogram() is simply to make this go back to the asking thing :) */
}
}
EDIT: also, where it says if( <somevariable> >= 7000), change 7000 to beer, so that way, if u change beer, you won't have to change this :)
Put a fflush(stdin) to clear the input before the last scanf
The program doesn't skip the third input data, it just scans the newline you press after the second input. To fix this, type scanf("%*c%c", &buy); instead of scanf("%c", &buy);. This little %*c scans and ignores the the character read from the input.
you can remove the buy variable from the printf call, it's unneeded
printf ("\nWould you like to buy a beer (y/n) ?",buy);
And replace char buy by char buy[2]; . because a sting is always terminated by /0.
You can also add a memset (buy, 0, sizeof(buy)), to be sure that memory is reset before you start to use it.

While Loop skipping scanf for it's condition.

I can't see why does the While loop just speed away and skipping the scanf for the char?
It would not even ask for my input and just loop like there's no tomorrow.
#include <stdio.h>
int main()
{
int number;
int multiply, ans;
char choice;
printf("-------------------------------------");
printf("\n MULTIPLICATION TABLE ");
printf("\n-------------------------------------");
do
{
printf("\nEnter an integer number:");
scanf("%d", &number);
printf("\nMultiplication of %d is :-\n", number);
printf("\n");
for(multiply=1; multiply<11; multiply++){
ans = number * multiply;
printf(" %d", ans);
}
printf("\n");
printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
scanf("%c", &choice);
printf("\n");
}
while(choice='Y');
printf("Thank You");
return 0;
}
scanf() doesn't do what you think it does (newline characters, buffering, etc.). It's preferred to use fgetc():
choice = fgetc(stdin);
For the same reason, you need to get rid of the trailing newline that
scanf("%d", &number");
leaves in the standard input buffer. To fix this, insert
fgetc(stdin);
after that particular call to scanf().
Also, C is not Pascal. The equality comparison operator - and the condition - you're looking for is
while (choice == 'Y')
the single equation mark denotes an assignment.
I think you need to use == operator for the comparison in while condition check as:
while(choice=='Y');
Currently you are using = operator, which is assigning Y to choice variable.
It has been a long time since I programmed in that language, but at a glance, you have:
while(choice='Y');
instead of:
while(choice=='Y');
== compares, = sets equal to. So the while loop is actually not checking the condition you're trying to set.

Resources