fp= fopen("Quiz.txt", "r");
fflush(stdin);
printf("Enter Name To Search:");
gets(srch);
if(srch==std[i].name)
{
printf("\n Student Name: %s", std[i].name);
printf("\n Roll Number :%d", std[i]. roll);
printf("\n First Quiz Marks :%d", std[i]. quiz1);
printf("\n Second Quiz Marks :%d", std[i]. quiz2);
printf("\n Third Quiz Marks :%d", std[i]. quiz3);
printf("\n Fourth Quiz Marks :%d", std[i]. quiz4);
printf("\n Fifth Quiz Marks :%d", std[i]. quiz5);
}
else{
printf("No Data Of %s", srch);
}
getchar();
fclose(fp);
I am not getting data related to search that user search suppose if user search their name if the name is available in a file then it returns with users name roll number and 5 quiz marks if not then return no data available
for string comparison, you have the possibility to use the function int strcmp(const char *s1, const char *s2);. The strcmp function returns 0 if and only if the two strings are identical. The returned value is negative if the first string is greater than the second and positive if it is not.
(don't forget to include the header #include <string.h>)
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 months ago.
So I was writing a quick program to get information about a patient from a hospital and it keeps skipping the scanf() at a certain point (at around line 34) and moves on to the scanf() after it. Here's the part that keeps bothering the life out of me:
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int main(void){
char choice_1, choice_2, *blood_group, *spec_conditions, *allergies;
printf("Enter the patient's medical details.\n\n");
printf("Enter your blood group: ");
scanf("%s",&blood_group);
printf("Does the patient have any allergies:(y/n)");
scanf("%c",&choice_2);
if (choice_2 == 'y'){
printf("Kindly enter the allergies: ");
scanf("%s",&allergies);
}else{
allergies = "No allergies";
}
printf("\nDoes the patient have any special conditions:(y/n)");
scanf("%c",&choice_1);
if (choice_1 == 'y'){
printf("Kindly enter the condtion: ");
scanf("%s",&spec_conditions);
}else{
spec_conditions = "No special conditions";
}
printf("Displaying details...\n");
sleep(2);
system("cls");
printf("\t\t\tPATIENT DETAILS\n");
sleep(1);
return 0;
}
Problem 1:
char *blood_group, *spec_conditions, *allergies;
scanf("%s",&blood_group);
scanf("%s",&allergies);
scanf("%s",&spec_conditions);
What this does is it attempts to write a string of an unknown length to the address of char * variables, resulting in a 'buffer' overflow if the string is larger than a pointer, or a wild pointer that points to a random location.
Do not pass the address of the pointer to scanf, pass the pointer itself. Furthermore, the pointer must point to writable memory. This can be done by declaring it as an array.
Problem 2:
scanf("%c") reads the newline left when the user hits enter to read the string and moves on. Use scanf(" %c") instead to skip leading whitespace and read the actual character.
Try:
int main(void){
char choice_1, choice_2, blood_group[256], spec_conditions[256], allergies[256];
printf("Enter the patient's medical details.\n\n");
printf("Enter your blood group: ");
scanf("%255s",blood_group);
printf("Does the patient have any allergies:(y/n)");
scanf(" %c",&choice_2);
if (choice_2 == 'y'){
printf("Kindly enter the allergies: ");
scanf("%255s",allergies);
}else{
strcpy(allergies, "No allergies");
}
printf("\nDoes the patient have any special conditions:(y/n)");
scanf(" %c",&choice_1);
if (choice_1 == 'y'){
printf("Kindly enter the condtion: ");
scanf("%255s",spec_conditions);
}else{
strcpy(spec_conditions, "No special conditions");
}
printf("Displaying details...\n");
sleep(2);
system("cls");
printf("\t\t\tPATIENT DETAILS\n");
sleep(1);
return 0;
}
I'm trying to understand the whole concept of pointers, structures, etc so I've created a program that gets user input for two different books and then swaps the info of the two books. I had no trouble doing that, however, a problem arose- when I pressed enter the name of the book would be plain blank and at the output I would, of course, see a blank space. My problem is, how am I able to limit the user to input any letter (A-Z, a-z) and not blank space?
A string of characters when input to an array, they get saved in consecutive memory addresses. We also know that 'NULL' is represented as '\0' in arrays.
With the above things in mind, I performed multiple tests in which, ALL of them failed to yield the desired results.
Below are some attempts that I made.
1st Attempt
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
2nd Attempt
while (strcmp(pBook1->name, ""))
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
Also, consider the following code as the source code of my program:
#include <stdio.h>
#include <string.h>
#define MAX 50
struct Books
{
char name[MAX];
int ID;
float price;
};
void swap(struct Books *, struct Books *);
void main()
{
struct Books Book1, Book2, *pBook1, *pBook2;
pBook1 = &Book1;
pBook2 = &Book2;
// Input for the 1st book
printf("\n 1st Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook1->name, MAX, stdin);
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook1->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook1->price);
// Input for the 2nd book
printf("\n 2nd Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook2->name, MAX, stdin);
while (pBook2->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook2->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook2->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook2->price);
printf("\n Let's swap the info of the two books...");
swap(pBook1, pBook2);
printf("\n The info of the two books is now:");
printf("\n------------------------------ \n 1st Book \n ------------------------------------");
printf("\n Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook1->name, pBook1->ID, pBook1->price);
printf("\n------------------------------ \n 2nd Book \n ------------------------------------");
printf("Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook2->name, pBook2->ID, pBook2->price);
}
void swap(struct Books *pB1, struct Books *pB2)
{
char temp[MAX];
strcpy(temp, pB1->name);
strcpy(pB1->name, pB2->name);
strcpy(pB2->name, temp);
int tempID = pB1->ID, tempPrice = pB1->price;
pB1->ID = pB2->ID;
pB2->ID = tempID;
pB1->price = pB2->price;
pB2->price = tempPrice;
}
fgets reads until it encounters EOF, \n or N-1 bytes have been read. So if a user of your program presses enter, it will read \n and stop. Which means that pBook1->name[0] == '\n'. That is why your check for equality with "" fails and why pBook1->name[0] == '\0' fails.
See this example.
That means that you need to check for \n and \0 in case the user entered Ctrl-D which is how you enter EOF on *nix systems.
When you press enter pBook1->name[0] will become \n. You can use some functions as strlen to be sure there something in name.
Computerizing health records could make it easier for the patients to share their health profiles and histories among their various health care professionals. A health clinic needs your help to computerize the patients' health records. The patient's records consist of first name, middle name, last name (including SR. JR., etc), gender, date of birth, height (in inches), weight (in pounds). The clinic requires the following features of the program:
read existing record from a file where each patient record is one line entry separating each data with comma
add additional records to file
a function to calculate and return patients age in 3yrs
a function that calculates body mass index with the given formula BMI=(weight-in-pounds X 703)/(height-in-inches X 2) or BMI = (weight-in-kgs)/(height-in-meters X 2)
search patient's name and display patient's information with age and BMI value including category
update patient's information on date of birth, height and/or weight and save updates to file
display all records in tabular format
So far what I have made is:
#include<stdio.h>
#include<stdlib.h>
main(){
FILE*fin;
char name,fname,mname,lname,ename,gender,ch,getch,patient;
int dob,month,day,year,height,weight;
fin=fopen("oldrec.c","w");{
printf("Error: File does not exists");
return 0;
}
{
printf("Add Record? y/n");
ch=toupper(getch);
if(ch='y')
break;
}while (1);
struct patient{
char name;
char fname[20];
char mname[20];
char lname[20];
char gender;
int dob;
int month;
int day;
int year;
int height;
int weight;
printf("/n Patient's Name");
printf("First Name: ");
scanf("%s", &patient.fname);
printf("Middle Name: ");
scanf("%s", &patient.mname);
printf("Last Name: ");
scanf("%s", &patient.lname);
printf("Gender: ");
scanf("%s", &patient.gender);
printf("Date of Birth");
printf("Month: ");
scanf("&d", &patient.month);
printf("Day: ");
scanf("&d", &patient.day);
printf("Year: ");
scanf("%s", %patient.year);
printf("Height: ");
scanf("%d", & patient.height);
printf("Weight: ");
scanf("%d", &patient.weight);
}
I have made another file already, but when I run the codes, it says "Error: File does not exist". What is wrong, and what are the codes for the other problems? Please help me! This is our final requirement on my data structure subject.
fin=fopen("oldrec.c","w");{ // no if
printf("Error: File does not exists"); // all statements will be executed
return 0; // and function will terminate here
}
Ofcourse it will show that message , no condition . No matter if fopen is successful without if all statements will be executed.
Put it in a if block witn a condition .
Write like this -
fin=fopen("oldrec.c","w");
if(fin==NULL){ // check if fin is NULL
printf("Error: File does not exists");
return 0;
}
Other problems are these statements -
scanf("%s", &patient.fname);
...
scanf("%s", &patient.mname);
...
scanf("%s", &patient.lname);
...
scanf("%s", &patient.gender); // use %c for reading char variable
...
scanf("%s", %patient.year); // use %d to read int
^ whats this
Write these statemetns like this -
scanf("%s", patient.fname);
...
scanf("%s", patient.mname);
...
scanf("%s", patient.lname);
...
scanf("%c", &patient.gender);
...
scanf("%d", &patient.year);
This question already has an answer here:
How to sort an array of structs in C?
(1 answer)
Closed 8 years ago.
I have created a stack system in C
It takes the First Name, Last name, and an employee number and the program runs fine.
#include<stdio.h>
#include<conio.h>
#define MAX 20
struct system
{
char first_name[15];
char surname[15];
}employee[20], temp;
int stack[MAX],front=-1,top=-1;
int i;
void push_element();
void pop_element();
void display_stack();
void display_first();
int main()
{
int option;
printf("STACK PROGRAM");
do
{
printf("\n\n 1.Push an element");
printf("\n 2.Pop an element");
printf("\n 3.Display stack");
printf("\n 4.Display first");
printf("\n 5.Display last");
printf("\n 6.Exit");
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1: push_element();
break;
case 2: pop_element();
break;
case 3: display_stack();
break;
case 4: display_first();
break;
case 5: display_last();
break;
case 6: return 0;
}
}while(option!=6);
}
void push_element()
{
printf("\n Enter the first name: ");
scanf("%s",employee[i].first_name);
printf("\n Enter the Last name: ");
scanf("%s",employee[i].surname);
int num;
printf("\n Enter the employee number: ");
scanf("%d",&num);
i++;
if(front==0 && top==MAX-1)
printf("\n You have entered more than 20. Please delete a current input to make room. ");
else if(front==-1&&top==-1)
{
front=top=0;
stack[top]=num;
}
else if(top==MAX-1 && front!=0)
{
top=0;
stack[top]=num;
}
else
{
top++;
stack[top]=num;
}
}
void pop_element()
{
top--;
return top;
}
void display_stack()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n List of employees:\n\n ");
printf(" Employee number First Name Surname\n\n");
for(i=front;i<=top;i++)
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
void display_first()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n The first Employee in the stack is:\n\n ");
printf(" Employee number First Name Surname\n\n");
for(i=front;i<=top;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
void display_last()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n The last Employee in the stack is:\n \n");
printf(" Employee number First Name Surname\n\n");
for(i=top;i<=front;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
I for the life of me cannot figure out how to sort the stack. I have tried other pieces of code and many different things, but none of them have came close to finding it
But I am wanting to sort it by alphabetical order. So not by entry time or Employee number, but by the First initial of the Surname
A search function is also required for this, and to be done by Employee number.
I have looked online, and the use of sorting and searching in a stack isn't a common thing, but I required to have it.
I am not good at C and I am fairly new to it. Any tips or things that may help me greatly would be appreciated. Also I apologies for any formatting errors, I'm fairly new to programming altogether and using software.
Your data structure doesn't directly record an employee number. You have the array stack which records the employee number, and the array employee which records names. You need to preserve the relationship stack[i] contains the employee number for employee[i] which means any sorting of the existing data structure has to sort two arrays in parallel. While it can be done, it is not the best way to fix the problems (and it is harder than it need be, and will require a custom sort function).
You should upgrade the data structure to include the employee number:
struct employee
{
int number;
char first_name[15];
char surname[15];
} employee[20];
Note that I've retagged the structure as struct employee (instead of struct system) since it seems more relevant to the content of the structure.
You can then use the qsort() function from the standard C library (declared in <stdlib.h>) and the techniques documented in the proposed duplicate (How to sort an array of structs in C?) to sort the data straight-forwardly. It is also easier to write your searching code.
You can also clean up the display code; you can have a single function that is passed an employee structure (or pointer to one). It will contain a single printf() statement that formats the data correctly. This saves you writing the same elaborate printf() code 3 times, making it easier to fix the formatting if (when) you need to do so. You can also avoid using tabs in the output (generally a good idea), leading to:
void print_employee(const struct employee *emp)
{
printf("%8d %-15s %-15s\n", emp->number, emp->first_name, emp->surname);
}
This will produce well aligned output unless your employee number grows to more than 8 digits (in which case, change the 8 to 10 or whatever). You can also generalize one step further if you wish, passing a FILE *fp argument to the function, and using fprintf(fp, "…", …) instead of printf().
You call the function:
print_employee(&employee[i]);
You might also consider a function to print the headings since you have that function call 3 times. Alternatively, you might just have a constant string at file scope that contains the correct headings which you use in 3 places. You could do that with the print_employee() function too; have a constant string at file scope that is the format you use.
Also, in your display_first() and display_last() functions, the loops are curious. You've written:
for(i=front;i<=top;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
You should realize (on review) that this is equivalent to:
i = front;
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
(If front is larger than top, then i = front is the only part of the loop executed; otherwise, the break is executed; either way, after the loop, i == front.)
The following code is a project I'm working on and after entering the details as in name and email it won't go to the next part of the code which is printing the price and then go to the next function. What did I do wrong??
Also, what can I do so that a customer can enter their details with spacing?
Thanks in advance.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int option,card_num,csc,phone_number;
char name,address,e_mail,registration;
void membership();
void payment();
int main()
{
membership();
return 0;
}
void membership()
{
printf("\tTHE CRUMP'S MEMBERSHIP");
printf("\n\n This membership ...");
printf("\n\n REGISTRATION [CONTRACTOR(A)/CORPORATION(B)]=");
scanf("%c",®istration);
switch (registration)
{
case 'A':
printf("\n\nEnter details without any spacing.");
printf("\nNAME:");
scanf("%s",&name);
printf("\nADDRESS:");
scanf("%s",&address);
printf("\nPHONE NUMBER:");
scanf("%d",&phone_number);
printf("\nE-MAIL:");
scanf("%s",&e_mail);
break;
case 'B':
printf("Enter details without any spacing.");
printf("\nNAME OF CORPORATION:");
scanf("%s",&name);
printf("\nADDRESS OF CORPORATION:");
scanf("%s",&address);
printf("\nPHONE NUMBER OF CORPORATION:");
scanf("%d",&phone_number);
printf("\nE-MAIL OF CORPORATION:");
scanf("%s",&e_mail);
break;
}
if (registration=='A')
printf("\n THE REGISTRATION FEE = |RM 50/MONTH |\t| RM 500/YEAR|");
else if (registration=='B')
printf("\n THE REGISTRATION FEE = |RM 200/MONTH |\t| RM 2200/YEAR|");
}
void payment()
{
printf("\n\nChoose method of payment: ");
printf("\n\t 1- Money Transfer \n\t 2-Debit Card\n");
scanf("%d",&option);
if (option==1)
{
printf("\nYou have chosen Money Transfer.");
printf("\nYou can transfer your money at our bank account --> 4365 4200 1471");
printf ("\n your membership will be confirmed when we have received the payment");
printf("\n************************************************************");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n your transaction completed...\n\n Enjoy your membership discount.");
}
else if (option==2)
{
printf("\nYou have chosen Credit/Debit card.");
printf("\n Please enter your Credit/Debit card number:");
scanf("%d",&card_num);
printf("\n Please enter CSC code:");
scanf("%d",&csc);
printf("\nYour membership will be confirmed when we have received the payment");
printf("\n*********************************************************\n\n");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n Your transaction is completed...\n\n Enjoy your membership discount.");
}
}
You are trying to read strings into char variables:
char name,address,e_mail,registration;
//...
scanf("%s",&name);
char only holds one character, not a string. If you want to read a string use an character array:
char name[100];
//...
and pass it to scanf like this:
scanf("%s",name);
because the array already decays to a pointer and taking the address is unnecessary.
Note that this requires you to set a limit for the name length. For example I choose 100-1 = 99 characters as limit. If the input is longer, undefined behaviour occurs, which is what you are experiencing right now.
Also note that you never call payment, so this will never be executed. If you want it to be executed after membership, then you need to call it:
int main()
{
membership();
payment();
return 0;
}
Your program has no call to payment() function thats why the program flow is not complete.