This question already has an answer here:
C Access violation writing location scanf_s
(1 answer)
Closed 1 year ago.
While the program is running , in the middle of it (after typing the Vaccine name ) it stops and gives me {Exception Thrown} can anyone help me fix this issue? I have also included a photo of the error it gives me
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int choose, dosage, quantity;
char code[10];
char name[32];
char produce[64];
float population;
{
printf("COVID-19 Vaccination System \n");
printf("1:- Inventory Creation \n");
printf("2:- Update Vaccine Quantities \n");
printf("3:- Search Vaccine \n");
printf("4:- Produce a list of all Vaccines and their distributed Quantities \n");
printf("5:- EXIT \n\n");
printf("==>");
scanf_s("\n%d", &choose);
if (choose == 1)
{
char ch;
FILE* cv;
errno_t err;
err = fopen_s(&cv, "vaccine.txt", "w");
for (int i = 0; i < 5; i++)
{
printf("Please Enter Vaccine Full information %d \n", i + 1);
printf(" Name of Vaccine : ");
scanf_s("\n%s", &name);
printf("Please Enter Vaccine Code %c \n", i + 1);
printf(" Vaccine Code : ");
scanf_s("\n%s", &code);
printf("Please Enter Vaccine Producing Country %c \n", i + 1);
printf("Producing Country : ");
scanf_s("\n%s", &produce);
printf("Please Enter Dosage Required %d \n", i + 1);
printf("Dosage Required (MAX=2 - MIN=1) : ");
scanf_s("\n%d", &dosage);
printf("Please Enter Population Covered %d \n", i + 1);
printf("Population Covered (%) : ");
scanf_s("\n%f", &population);
printf("Please Enter Vaccine Quantity %d \n", i + 1);
scanf_s("\n%d", &quantity);
fprintf("%s %s %s %d %f %d", name, code, produce, dosage, population, quantity);
}
}
}
return 0;
}
The line
fprintf("%s %s %s %d %f %d", name, code, produce, dosage, population, quantity);
is wrong. You have to pass a file pointer as the first argument of fprintf(). It should be:
fprintf(cv, "%s %s %s %d %f %d", name, code, produce, dosage, population, quantity);
Also
You should check if fopen_s succeeded before proceeding to next operation and stop operation if it failed.
You should remove & before the array names (code, name, produce) used in scanf_s. Array in expressions (excluding some exceptions) are automatically converted to pointers to the first element, so no explicit & is not needed here. Also it will make the type wrong scanf() expects char* for %s, but things like &code are an pointers to arrays (like char(*)[10]).
Related
I want to take input from user using structure. So I'm using the code like below. But it's not printing the values which I'm entering. Can anyone help me?
#include <stdio.h>
int main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b1, b2;
printf("Enter the Name, Price and Pages of Book 1: ");
scanf("%c %f %d", &b1.name, &b1.price, &b1.pages);
printf("Enter the Name, Price and Pages of Book 2: ");
scanf("%c %f %d", &b2.name, &b2.price, &b2.pages);
printf("Here is the data you've entered: \n");
printf("Name: %c Price: %f Pages: %d\n", b1.name, b1.price, b1.pages);
printf("Name: %c Price: %f Pages: %d\n", b2.name, b2.price, b2.pages);
return 0;
}
But I'm not getting the output as desired. My
Output Image
Your question is similar to this one: scanf() leaves the newline character in the buffer
And can be corrected like this:
#include <stdio.h>
int main()
{
struct book
{
char name;
float price;
int pages;
};
char buffer[255];
struct book b1, b2;
printf("Enter the Name, Price and Pages of Book 1: ");
scanf(" %c %f %d", &b1.name, &b1.price, &b1.pages);
printf("Enter the Name, Price and Pages of Book 2: ");
scanf(" %c %f %d", &b2.name, &b2.price, &b2.pages);
printf("Here is the data you've entered: \n");
printf("Name: %c Price: %f Pages: %d\n", b1.name, b1.price, b1.pages);
printf("Name: %c Price: %f Pages: %d\n", b2.name, b2.price, b2.pages);
return 0;
}
Note the leading space before the %c input.
I'm new to C, and currently trying to practice on some simple codes, and I'm currently stuck with that next one.
After entering the first customer data, and repeat the code... View_customer function fails to show the saved data, and when I try to go to enter a second account data, it fails at the second entry.
#include<stdio.h>
#include<stdlib.h>
typedef struct cust{
char name[60];
int acc_no,age;
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
} cust;
void new_account(int num);
void view_account(int num);
int main()
{
cust customers[10];
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
do{
printf("\n How can we serve you today? \n 1.Create a new account \n 2.Print an existing Account info \n ");
scanf("%d",&n);
if (n==1)
{
new_account(cutomer_number);
cutomer_number++;
}else {
printf("Please enter your Cust number: ");
scanf(" %d",&cutomer_num2);
view_account(cutomer_num2);
};
printf("\n Press Y to continue. Press any Key To Exit: ");
scanf(" %c",&answer);
}while (answer == 'Y' || answer == 'y');
return 0;
}
void view_account(int n)
{
cust customers[n];
printf("Your name is %s \n ", customers[n].name);
printf("Your age is %d \n", customers[n].age);
printf("Your address is %s \n", customers[n].address);
printf("Your citizenship is %s \n", customers[n].citizenship);
printf("Your phone number is %f \n", customers[n].phone);
printf("Your account type is %s \n", customers[n].acc_type);
};
void new_account(int n)
{
cust customers[n];
customers[n].acc_no = n;
printf("You are the customer number %d \n", customers[n].acc_no);
printf("Please, Enter your name: ");
scanf("%s", &customers[n].name);
printf("Please, Enter your age:");
scanf(" %d", &customers[n].age);
printf("Please, Enter your address: ");
scanf(" %s", &customers[n].address);
printf("Please, Enter your citizenship: ");
scanf(" %s", &customers[n].citizenship);
printf("Please, Enter your phone number: ");
scanf(" %f", &customers[n].phone);
printf("Please, Enter your account type: ");
scanf(" %s", &customers[n].acc_type);
}
>
Each of your three functions declares its own customers array variable, so each of them has their own memory for the customer data. Moreover, the array of new_account goes out of scope at the end of the function, so you can no longer safely access the data. Because of how C compilers typically work, the customer data is not immediately erased from memory, so your view_account function might still be able to read it, but that is what is called "undefined behavior". Which means it might work, or it might not.
Try to pass down the array from the main function to the other two functions in parameters. Or, to make things simpler at first, you could also turn the local customers variable of main into a global variable.
cust customers[10];
int main(int argc, char *argv[])
{
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
...
}
void view_account(int n) {
printf("Your name is %s \n ", customers[n].name);
...
}
void new_acccount(int n)
{
customers[n].acc_no = n;
...
}
Note that there are further issues in your code, like not checking the return value of scanf or overflowing the char arrays of the struct if you enter too many characters (missing bounds and length checking), or being able to enter more than 10 customers and accessing out of bounds of the customers array, or not using customers[0] (because your customer_number starts at 1, but array indices are 0-based). But I will not go into further details here to keep the answer focused.
#include<stdio.h>
#include<stdlib.h>
char* genderfun(){
char *gender;
char g;
printf("\n >>> enter your gender (M/F/T): ");
//g = getc(stdin);
scanf(" %c",&g);
if(g == 'M'){
gender = "Male";
}else if(g == 'F'){
gender = "Female";
}else{
gender = "Transgender";
}
return gender;
}
float percentagecalculator(){
float math,physics,chemistry,english,other,percent;
printf("\n >>> Enter maths marks: ");
scanf("%f",&math);
printf("\n >>> Enter english marks: ");
scanf("%f",&english);
printf("\n >>> Enter physics marks: ");
scanf("%f",&physics);
printf("\n >>> Enter chemistry marks: ");
scanf("%f",&chemistry);
printf("\n >>> Enter additional subject marks: ");
scanf("%f",&other);
percent = ((math+english+physics+chemistry+other)/500)*100;
return percent;
}
void main(){
char *name;
char* genders;
int age,count;
float percent;
printf(">>> Enter your name: ");
scanf(" %c",&name);
//fflush(stdin);
printf("\n >>> Enter your age: ");
scanf("%d",&age);
genders = genderfun();
percent = percentagecalculator();
if(percent < 33){
printf("\n name : %c \n age : %d \n gender : %c \n Percentage : %f \n Status : Failed",name,age,genders,percent);
}else if(percent >= 33){
printf("\n name : %c \n age : %d \n gender : %c \n Percentage : %f \n Status : Passed",name,age,genders,percent);
}else{
printf("\n Error");
}
}
My code is not taking a name more than one character as input and if I try that it skips everything and programs ends and also the gender is not being returned but instead it prints very absurd values in console. Please help me fix this bug.
Well, I've been reading your code and there are several problems. Here are the ones that I've found out:
Return type of 'main' is not 'int'.
In main: Unused variable 'count'
Missing spacing and camel notation for function
You're assuming to read string, but you are actually reading a char (e.g. the name, the creation of gender string, and so on).
You're trying to insert a string, but reading a char, you pollute all your input buffer.
You're using fflush(...). Please check here why you shouldn't use it: Using fflush(stdin)
In order to use strings (or array of char) while reading dynamically names and assigning chars to an array of char, you need dynamic memory or at least VLA (in the following code, you will find the implementation with Dynamic Memory).
In the 'percentage calculator' function you are assuming to take multiple values for each subject. Actually, you are taking only one mark for each subject.
You are going wrong while reading a string. Here's how to properly do that:
How to read string from keyboard using C?
You are trying to print a char instead of a string in the final print.
Please do a better naming of your variables and your functions.
I'm gonna attach here a working code for your question:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define stringSize 256
char * readGender() {
fseek(stdin, 0, SEEK_END);
char * gender = (char *) malloc(stringSize);
char g;
if (!gender) exit(EXIT_FAILURE);
printf("\n >>> Enter your gender (M/F/T): ");
g = getchar();
if (g == 'M') {
strcpy(gender, "Male");
}else if(g == 'F') {
strcpy(gender, "Female");
}else {
strcpy(gender, "Transgender");
}
gender = (char *) realloc(gender, strlen(gender) + 1);
if (!gender) exit(EXIT_FAILURE);
return gender;
}
float percentageCalculator() {
float math, physics, chemistry, english, other, percent;
printf("\n >>> Enter math mark: ");
scanf("%f", &math);
printf("\n >>> Enter english mark: ");
scanf("%f", &english);
printf("\n >>> Enter physics mark: ");
scanf("%f", &physics);
printf("\n >>> Enter chemistry mark: ");
scanf("%f", &chemistry);
printf("\n >>> Enter additional subject mark: ");
scanf("%f", &other);
percent = ((math + english + physics + chemistry + other) / 500) * 100;
return percent;
}
int main() {
char * gender;
int age;
float percentage;
char *name = (char *) malloc(stringSize);
if (!name) exit(EXIT_FAILURE);
printf(">>> Enter your name: ");
fgets(name, sizeof(stringSize - 1), stdin);
name = (char *) realloc(name, strlen(name));
if (!name) exit(EXIT_FAILURE);
fseek(stdin, 0, SEEK_END);
printf("\n >>> Enter your age: ");
scanf("%d", &age);
gender = readGender();
percentage = percentageCalculator();
if (percentage < 33) {
printf("\n name : %s \n age : %d \n gender : %s \n Percentage : %f \n Status : Failed\n", name, age, gender, percentage);
} else if (percentage >= 33) {
printf("\n name : %s \n age : %d \n gender : %s \n Percentage : %f \n Status : Passed\n", name, age, gender, percentage);
} else {
printf("\n Error");
}
return 0;
}
Note that I've used fseek(...) as suggested here: How to clear input buffer in C? in order to read correctly char and integers together.
fseek(...) works on some systems; if not, then it is not surprising as nothing guarantees that it will work when standard input is an interactive device (or a non-seekable device like a pipe or a socket or a FIFO, to name but a few other ways in which it can fail).
If you need that it has to be portable, then check the link that I've placed before. Hope that it was helpful.
Next steps:
Adding user input error handling
Use a switch in 'readGender(...)' instead of the final triple if
Cheers, Denny
#include<stdio.h>
#include<stdlib.h>
/*
# Mistakes to avoid in future
1. use fgets(name_of_inputVariable,size,stdin) instead of scanf
2. use %s for strings rather than %c
3. use *name_of_variable for the strings
4. use fflush(stdin) only when program is skipping a certain step.
5. use switch statements for the character stuff.
*/
char* getGender(){
char *gender,g;
printf(">>> enter a gender (m/f/t): ");
scanf("%c",&g);
switch(g){
case 'm':
gender = "Male";
break;
case 'f':
gender = "Female";
break;
case 't':
gender = "Transgender";
break;
default:
gender = "prefer not to say";
}
return gender;
}
float percentageCalculator(){
float math,physics,chemistry,english,other,percent;
printf("\n >>> Enter maths marks: ");
scanf("%f",&math);
printf("\n >>> Enter english marks: ");
scanf("%f",&english);
printf("\n >>> Enter physics marks: ");
scanf("%f",&physics);
printf("\n >>> Enter chemistry marks: ");
scanf("%f",&chemistry);
printf("\n >>> Enter additional subject marks: ");
scanf("%f",&other);
percent = ((math+english+physics+chemistry+other)/500)*100;
return percent;
}
void main(){
char name[35];
char *gender;
int age,count;
float percent;
printf("\n >>> Enter your name: ");
fgets(name,35,stdin); //fgets is way better than scanf. you can use exact value 35
//scanf("%34s",&name); // scanf is a little buggy. you need to add one value less to prefent buffer overflow i.e. "%34s"
//fflush(stdin); // fflush do solved problem as it took entire name but only printed first character in output. It's fixed via fgets now.
printf("\n >>> Enter your age: ");
scanf("%d",&age);
fflush(stdin); // It was skipping gender ask step, so fflush fixed it by cleaning the overflow buffer. (fixed)
gender = getGender(); // getGender have some problem. It prints very absurd values in output console. (fixed)
percent = percentageCalculator(); // percentage calculator is working 100% fine. I got my accurate percentage and status lol ;)
if(percent < 33){
printf(" name : %s \n age : %d \n gender : %s \n Percentage : %f \n Status : Failed",name,age,gender,percent);
}else if(percent >= 33){
printf(" name : %s \n age : %d \n gender : %s \n Percentage : %f \n Status : Passed",name,age,gender,percent);
}else{
printf("\n Error");
}
}
Here I have finally fixed all issues in my code and now my program is working correctly. Thanks for some ideas stackoverflow community.
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.
I'm writing a program that basically just takes a bunch of user input and Outputs it in the form of a check. My problem is that I'm entering 2 sentences and while the second one is fine it completly skips the first one! and the user last name is working but the first name just outputs "z" it is the weirdest thing and my teachers philosophy is figure it out yourself. So can anyone possibly help me?? Here is my code...
#include<stdio.h>
#include<string.h>
int main()
{
char date[8];
int checkNum;
char payeeFirst[10];
char payeeLast[10];
double amount;
char memo[50];
char wordAmount[100];
printf("Please enter the date: ");
scanf("%s", &date);
printf("Please enter the check number: ");
scanf("%d", &checkNum);
printf("Please enter the payee First name: ");
scanf("%s", &payeeFirst);
printf("Please enter payee last name: ");
scanf("%s", &payeeLast);
printf("Please enter amount: ");
scanf("%d", &amount);
printf("Please enter amount in words: ");
fgets (wordAmount, sizeof(wordAmount)-1, stdin);
printf("Please enter memo: ");
fgets (memo, sizeof(memo)-1, stdin);
printf(" \n");
printf("Date: %s .\n", date);
printf("Check Number: %d .\n", checkNum);
printf("Payee: [%s] [%s] .\n", payeeFirst, payeeLast);
printf("Amount: %d .\n", amount);
printf(" Check %d \n", checkNum);
printf(" Date: %s \n", date);
printf("Pay to the\n");
printf("Order of %s %s $%d \n", payeeFirst, payeeLast, amount);
printf("%s", wordAmount);
printf(" \n");
printf(" \n");
printf("Memo: %s \n", memo);
return 0;
}
Your scanf calls all leave the '\n' in the stream (the next scanf will ignore it though).
The first fgets reads an empty string (well ... a string containing a single '\n').
Try reading the numbers with fgets too (to a temporary buffer) and sscanf from the buffer to the correct variable. This way all the '\n' will be accounted for.