Why does it skip my command in C ? please check it - c

#include <stdio.h>
int main()
{
int inpa, med, oper, day, total;
char agree;
printf(" Bach Mai Hospital");
printf("\n\nHello, please enter your fee and we will calculate\npayment based on your insurance\n");
printf("How many days have you been in the hospital ");
scanf("%d", &day);
printf("How much is your medicine fee ");
scanf("%d", &med);
printf("Have you undergone surgery (Yes or No)");
scanf("%s", &agree);
switch(agree){
case 'Y':
printf("Enter your surgery fee ");
scanf(" %d", &oper);
break;
case 'N':
oper = 0;
break;
};
printf("%s", agree);
inpa = day * 15000;
printf("Your total fee\n");
printf("Inpatient fee: %-10d x 15000 = %d\n", day, inpa);
printf("Medicine fee: %-10d\n", med);
printf("Surgery fee: %-10d\n", oper);
total = inpa + med + oper;
printf("\n\nYou pay: %d\n", total);
return 0;
}
It skips my command from when I enter &oper
printf("Enter your surgery fee ");
scanf(" %d", &oper);
And it is the result
Bach Mai Hospital
Hello, please enter your fee and we will calculate
payment based on your insurance
How many days have you been in the hospital 8
How much is your medicine fee 90000000
Have you undergone surgery (Yes or No)Yes
Enter your surgery fee 80000000
PS D:\Desktop\Cprogram>
I would be so thankful if someone explain for me why
previously I have trouble with the "agree" variable which I declare a char but it understands "agree" as int. Thank you

printf("%s") expects a null character(\0). Whenever you want to print a character, you should use %c rather than %s.So replace printf("%s", agree); with print("%c",agree);, then everything works well.

printf("%s", agree);
This line seems to cause issue because:
agree is a char variable in stack and hold only 1 byte
When printf with %s, it is expected that you provide an char array end with value 0 which is string terminator.
Because of this when you call printf("%s", agree);, it will trigger a call to a string at address 'Y' or in hex value 0x59. And the access to this address is illegal and will cause undefined behavior for your program.

Related

While loop not stopping in C programmming

int math=0,phy=0,che=0,avg=0,cprg=0,n,i=1,sum=0,large;
char name, roll_no, dept;
printf("\n How many students : ");
scanf("%d", &n);
while(i<=n)
{
printf("NAME : ");
scanf("%s", &name);
printf("DEPARTMENT :");
scanf(" %s", &dept);
printf("ROLL NUMBER :");
scanf("%s", &roll_no);
printf("☻ MATHS MARK :");
scanf(" %d", &math);
printf("☻ PHYSICS MARK : ");
scanf("%d", &phy);
printf("☻ CHEMISTRY MARK :");
scanf(" %d", &che);
printf("☻ C Programming :");
scanf(" %d", &cprg);
printf("\n");
avg = math+phy+che+cprg;
avg=avg/4;
append(&head, avg);
i++;
}
return 0;
}
Here is some of my code. I need to run this loop for the number of times the user enters in the input,
and the loop is not ending in VS Code even though it works fine in online GDB.
Your variables name, roll_no, and dept are just a single character, but you treat them (with scanf) as though they are strings. I think you want to declare them as strings as follows:
char name[50], roll_no[10], dept[10];
adjusting the string sizes as needed to hold the data. Because you are writing data beyond what is allocated you get undefined behavior.
You will also need to remove the & in the scanf call for each of these variables, e.g.:
scanf("%49s", name);

Two scanf functions but one reads a different value

I'm struggling in letting the program read the variable total that was previously input after asking for the input for the variable month. The total is always 28257 and I don't know why.
I found out using " %c" on line 11 works, but I would like to know why "%s" doesn't.
#include <stdio.h>
int main(void) {
int total;
char month;
float sales;
printf ("Enter total amount collected (-1 to quit): ");
scanf("%d", &total);
printf("Enter name of month: ");
scanf("%s", &month);
printf("total collections : $ %d\n", total);
sales = (total/1.09);
printf("sales : $ %.2f\n", sales);
printf("county sales tax: $ %.2f\n", sales * 0.05);
printf("state tax: $ %.2f\n", sales*0.04);
printf("total sales tax collected: $ %.2f\n", sales *0.05 + sales *0.04);
return 0; }
you declared month as character, so you should use %c for input. %s is used for input character array. and before scanf("%c", &month);, also use getchar();.
getchar();
scanf("%c", &month);

How do I get multiple lines to print after ending this logical loop

Me again. The C rookie. I am working on an assignment to write a program that prompts a user to enter info after which the program should list back out the data that was entered. My code only prints the last record info that is entered.
For example, I enter the following info for employee #1 "Rookie Coder" as the first employee name and enter 25 and 40 for hourly wage and hours worked, respectively. Then, I enter the following info for employee #2 "Slow Learner" as the 2nd employee name and enter 20 and 45 for hourly wage and hours worked, respectively. The program only prints the info related to "Slow Learner". But I want to print out the info for both records entered.
Can someone please offer guidance on what I'm missing to get both records to print? Thank you from the C Rookie
// C Libraries Used
#include <stdio.h>
#include <math.h>
#include <string.h>
// Constant declerations
const float OTPAYFACTOR = 1.5;
FILE *userinputfile; //disk file (for input)
// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [21];
float hrsworked;
float hrwage;
int count;
char again;
// Function Prototypes
// M A I N F U N C T I O N
int main (void){
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", &deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
do {
count++; // Increment the counting variable
printf("Enter employee #%d: ", count);
scanf("%s %s", &firstname, &lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
} while (again != 'N' && again != 'n');
printf("End of processing.");
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
return 0;
}
You only have one set of variables that you use on each iteration of the loop. Anything stored the first time through the loop is overwritten the second time through the loop. So you'll only ever store the most recently entered set of values.
You want to declare each of the variables that are taking data as an array, that way you can save multiple values.
char deptname [5][21];
char firstname [5][10];
char lastname [5][10];
char fullname [5][21];
float hrsworked[5];
float hrwage[5];
...
do {
printf("Enter employee #%d: ", count+1);
scanf("%s %s", &firstname[count], &lastname[count]);
strcpy(fullname[count], firstname[count]);
strcat(fullname[count], " ");
strcat(fullname[count], lastname[count]);
printf("Enter the hourly wage of %s: ", fullname[count]);
scanf("%f", &hrwage[count]);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked[count]);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
count++; // Increment the counting variable
} while (again != 'N' && again != 'n');
Then you need to loop through the array to print each element:
int i;
for (i=0; i<count; i++) {
printf("%s, $%0.2f, %0.2f: \n", fullname[i], hrwage[i], hrsworked[i]);
}
:) naive from your side but don't worry. You are storing only the last data into the fullname, hrwage, hrsworked, so only the last output is saved there. You need a better data structure to store the data as they are inserted by user.
1) If you know how many inputs there will be you can use a predefined array of strings for strings for the name and floats for the hours and wage.
2) if you don't know then you will need an scaling data structure like for example a list in order to put/add/append elements to it ;)
for C Arrays check this and for Lists in C check this
Then last but not least after you fill them with the input you just need to loop with a for / while loop in order to print the array or list.
Hope this will help!
remove the & symbol from below statement because deptname itself is string
scanf("%s", &deptname);
do same from below statements also
scanf("%s %s", &firstname, &lastname);
you want to print all records but at last there is only one printf so obviously it prints only last employee records
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
if you wants to prints all employee data after giving 'N' option, you should store information before that, my suggestion is put all entries inside structure and then take array of structure and store every time.

Issue with learning C scanf function when program is run (no errors during compile) C programming absolute beginners guide Chapter 8

I typed the following code verbatim from the book:
// Ex program #2 from Ch 8 of ABGTC
// File Ch8Ex2.c
// This is a sample program that asks users for some basic data and prints it on screen in order to show what was entered
#include <stdio.h>
main()
{
float cost;
char topping[24];
int slices;
int month, day, year;
// The first scanf will look for a floating-point variable, the cost of a pizza
// If the user doesn't enter a $ before the cost, it could cause problems
printf("How much does a pizza cost in your area? Enter as $XX.XX\n");
scanf(" $%f", &cost);
// The pizza topping is a string, so your scanf doesn't need an &
printf("What is your favorite one-word pizza topping?\n");
scanf(" %s", topping);
printf("How many slices of %s pizza can you eat in one sitting?", topping);
scanf(" %d", &slices);
printf("What is today\'s date (enter it in XX/XX/XX format).\n");
scanf(" %d/%d/%d", &month, &day, &year);
printf("\n\nWhy not treat yourself to a dinner on %d/%d/%d", month, day, year);
printf("\nand have %d slices of %s pizza!\n", slices, topping);
printf("It will only cost you $%.2f!\n\n\n", cost);
return 0;
}
Zero errors arise when I compile (Using Code:Blocks, as recommended and used in the book); yet, once I run the program, after entering the first bit of user data requested (price of a slice of pizza, let's say I said it would be 03.45), the program prints out:
"What is your favorite one-word pizza topping?"
"How many slices of 03.45 pizza can you eat in one sitting?"
It feels like it is skipping the scanf line following the printf "What is your favorite...." and not only prompting the following printf line of "How many slices....", but inserting the 03.45 as the character array/string value that should have been entered by the user in the previous line.
I've tried a few different tweaks that have come to mind, but for the life of me I cannot figure out what I've done wrong. Any ideas?
The problem was that I wasn't using $ while inputting my response. When answering the first question of "How much does a pizza cost in your area? Enter as $XX.XX", I was responding 03.45, when I should have been responding $03.45 due to the scanf being $%f. Removing the $ from "$%f" and leaving the rest the same still yields the result desired in the final print functions.
Hopefully this helps somebody else using this book!
You do not check the return value of scanf(). scanf() returns the number of inputs correctly parsed and stored.
In case of failure, such as not matching a missing $ for format string " $%f", the offending input stays in standard input and will be read by the next call to scanf() or any other input function.
You can correct the program by reading input with fgets() and then parsing it with sscanf() until a correct conversion is performed or end of file is reached.
Note that you should protect the format %s to prevent buffer overflow: pass the maximum number of characters to read as scanf(" %23s", topping);
Here is an example:
#include <stdio.h>
int main(void) {
char line[80];
float cost;
char topping[24];
int slices;
int month, day, year;
for (;;) {
printf("How much does a pizza cost in your area? Enter as $XX.XX\n");
if (!fgets(line, sizeof line, stdin))
return 1;
if (sscanf(line, "$%f", &cost) == 1)
break;
printf("invalid input\n");
}
for (;;) {
printf("What is your favorite one-word pizza topping?\n");
if (!fgets(line, sizeof line, stdin))
return 1;
if (sscanf(line, "%23s", topping) == 1)
break;
printf("invalid input\n");
}
for (;;) {
printf("How many slices of %s pizza can you eat in one sitting?\n", topping);
if (!fgets(line, sizeof line, stdin))
return 1;
if (sscanf(line, "%d", &slices) == 1)
break;
printf("invalid input\n");
}
for (;;) {
printf("What is today\'s date (enter it in XX/XX/XX format).\n");
if (!fgets(line, sizeof line, stdin))
return 1;
if (sscanf(line, "%d/%d/%d", &month, &day, &year) == 3)
break;
printf("invalid input\n");
}
printf("\n\nWhy not treat yourself to a dinner on %d/%d/%d\n",
month, day, year);
printf("and have %d slices of %s pizza!\n", slices, topping);
printf("It will only cost you $%.2f!\n\n\n", cost);
return 0;
}
You are missing to flush the standard input after taking float variable as input.
Just use the following code given below and it will solve your problem.
#include <stdio.h>
main()
{
float cost;
char topping[24];
int slices;
int month, day, year;
printf("How much does a pizza cost in your area? Enter as $XX.XX\n");
scanf(" $%f", &cost);
fflush(stdin); //Just add this line here and your problem is solved.
printf("What is your favorite one-word pizza topping?\n");
scanf(" %s", topping);
printf("How many slices of %s pizza can you eat in one sitting?\n", topping);
scanf(" %d", &slices);
printf("What is today\'s date (enter it in XX/XX/XX format).\n");
scanf("%d/%d/%d", &month, &day, &year);
printf("\n\nWhy not treat yourself to a dinner on %d/%d/%d", month, day, year);
printf("\nand have %d slices of %s pizza!\n", slices, topping);
printf("It will only cost you $%.2f!\n\n\n", cost);
return 0;
}

Variables retaining value after program is terminated, how to prevent? C

This is a program that asks the user to input Shipping information about selling bikes, pretty lame. At the end when it prints out the number of bikes order, and the total cost, the numbers get screwed up. The previously entered amounts seem to be sticking in the memory. How do I fix this? If that is not the problem I would not mind being told so :)
#include <stdio.h>
#include <math.h>
//structure
typedef struct
{char cust_name[25];
char add_one[20];
char add_two[20];
}ORDER;
ORDER order;
int main(void){
fflush(stdin);
system ( "clear" );
//initialize variables
double number_ordered = 0;
double price;
char bike;
char risky;
double m = 359.95;
double s = 279.95;
//inputs for order
printf("Enter Customer Information\n");
printf("Customer Name: ");
scanf(" %[^\n]s", &order.cust_name);
printf("\nEnter Street Address: ");
scanf(" %[^\n]s", &order.add_one);
printf("\nEnter City, State, and ZIP: ");
scanf(" %[^\n]s", &order.add_two);
printf("\nHow Many Bicycles Are Ordered: ");
scanf(" %d", &number_ordered);
printf("\nWhat Type Of Bike Is Ordered\n M Mountain Bike \n S Street Bike");
printf("\nChoose One (M or S): ");
scanf(" %c", &bike);
printf("\nIs The Customer Risky (Y/N): ");
scanf(" %c", &risky);
system ( "clear" );
//print order
printf("\n**********Shipping Instructions**********");
printf("\nTo: %s\n %s\n %s", order.cust_name, order.add_one, order.add_two);
if (bike == 'M' || bike == 'm')
printf("\n\nShip: %d Mountain Bikes", number_ordered);
else
printf("\n\nShip: %d Street Bikes", number_ordered);
if (bike == 'M' || bike == 'm')
price = number_ordered * m;
else
price = number_ordered * s;
if (risky == 'Y' || risky == 'y')
printf("\nBy Freight, COD %d\n", price);
else
printf("\nBy Freight, And Bill The Customer %d\n", price);
printf("*****************************************\n");
return 0;
}
You are printing number_ordered and price, which are doubles, using %d. %d is only for integer types. Use %lf to printf or scanf doubles.
The formats for both your scanf and your printf are wrong, so you're neither reading nor writing your values properly.

Resources