#include <stdio.h>
#include<stdlib.h>
int main()
{
char first[10], last[10], id[10];
int stdnum;
FILE *fptr;
fptr = fopen("C:\\c\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
else
{
//first name
printf("Enter name: ");
scanf("%s", first);
fprintf(fptr,"%s ",first);
//last name
printf("Enter last name: ");
scanf("%s ", last);
fprintf(fptr,"%s", last);
//id
printf("Enter id: ");
scanf("%s %d", id, &stdnum);
fprintf(fptr,"%s\n", id);
fprintf(fptr,"%d\n", stdnum);
fclose(fptr);
return 0;
}
}
I am writing a program that asks user for name, last name and student number. Student number format is lowercase letter followed by 8 digits.
when i run this code, I can enter first and last name. After i enter last name and hit enter in cygwin, the console gives me a blank line and I MUST type atleast a charcter or a number into it for it to display "enter student id".
Enter name: bob
Enter last name: jones
1
Enter id: a00998877
then the file output is something like this:
"bob jones11"
I want the output to be something like this:
"Bob Jones a00998877"
What am i doing wrong?
Why are you scanning in two inputs in this line:
scanf("%s %d", id, &stdnum);
id is a char array and will be able to hold alphanumeric input. You can remove the use of stdnum.
scanf("%s", id);
I have an example-with-stdin-stdout
char first[10], last[10], id;
id is a single char no need for an array.
scanf("%s", last);
Removed space after s
scanf(" %c%d", %id, &stdnum)
changed id to char from string
fprintf(fptr,"%c\n", id)
Same here, changed to char
Related
I'm writing a program for an employee database and I'm writing the function to add an employee. I'm getting a bus error after my final prompt to scan in info. I'm pretty sure its to do with my scanf statement as I have a print statement right after that is not printing. Why would I be getting this error?
The prompt in question is for reading in job title.
void addEmployee(void)
{
char *name;
char gender;
int age;
char *title;
printf("Enter name: \n");
scanf(" %100s", name);
scanf("%*[^\n]%*c");
printf("Enter gender: \n");
scanf(" %1c", &gender);
scanf("%*[^\n]%*c");
printf("Enter age: \n");
scanf(" %d", &age);
scanf("%*[^\n]%*c");
printf("Enter job title: \n");
scanf(" %100s", title);
scanf("%*[^\n]%*c");
printf("Test");
printf("The employee you've entered is: %s %c %d %s \n", name, gender, age, title);
Employee newEmp = {*name, gender, age, *title};
if(employeeList[0] == NULL)
{
employeeList[0] = &newEmp;
nodeCount++;
}
}
Code is passing in an uninitialized pointer.
char *name; // Pointer 'name' not initialize yet.
printf("Enter name: \n");
// 'name' passed to scanf() is garbage.
scanf(" %100s", name);
Instead, pass a pointer to an existing array
char name[100 + 1];
printf("Enter name: \n");
// Here the array 'name' coverts to the address of the first element of the array.
// scanf receives a valid pointer.
scanf("%100s", name);
I have homework in my C programming class.
I have to input 3 people's information about name, major, ID(ex. 9304171)and output to console
'name, birth(yyyy-mm-dd), leep year, nationality, sex, major'.
I tried to that, but my scanf_s wasn't activated.
if i try to activate to my code, char array can activated, but my integer array can't activated.
char name[4]; // name
char major[4]; // major
int id[7] = {}; // ID
// Input name, major, ID
printf("Name : ");
scanf_s("%s \n", &name, 4);
printf("Major : ");
scanf_s(" %s \n", &department, 4);
printf("ID : ");
scanf_s("%d \n", id);
My English ability is so fool... but it is make me so angry, i begging to help..
plz, sombody help me T.T
Declare something like:
char name[50], major[50];
int id; // array removed
You can use fgets() if you're having issues with scanf_s(), I suspect you've given such short number of elements for name array (i.e. 4) and that's something relatable with the error. Try the following using fgets():
printf("Name: ");
fgets(name, 50, stdin); // fgets buffered for 50 elements
printf("Major: ");
fgets(major, 50, stdin); // fgets ...
printf("ID: ");
scanf("%d", &id); // scanf() can be used here
Let's take a look at a sample output (no errors):
// INPUT
Name: John Doe
Major: Something
ID: 101
// OUTPUT
Name: John Doe
Major: Something
ID: 101
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);
Is it possible to read a character and an integer in one time?
Like this:
char name[32];
int age;
printf("Give name and age: ");
scanf("%s%d%*c", name, &age);
It blocks all the time.
UPDATED: You only accept input but not printing any thing. See the below code ( working and tested )
#include <stdio.h>
int main(void) {
char name[32];
int age;
printf("Give name and age: ");
scanf("%31s%d", name, &age);
printf("Your name is %s and age is %d",name,age);
}
intput: Shaz 30
Output : Your name is Shaz and age is 30
char name[32];
int age;
printf("Give name and age: ");
scanf("%31s%d", name, &age);
If the input string is longer than 31 characters, the value read for age will be affected, this is where fgets comes in handy.
Do not read both the name and age on the same line input. Read the name first to force the user to enter a new line so you can handle the entire line as the input name.
Read fgets
It is one of the method
CODE
#include<stdio.h>
char name[32],age;
int main()
{
printf("Enter name and age: ");
scanf("%s%d", name, &age);
printf("\nNAME : %s AGE : %d",name,age);
}
OUTPUT Refer under the image
I have tested your code, there is no error. Maybe you should only add printf() to print the answer.You will find you can get the same answer with what you have printed.
EDIT: If input is Colin 23(the space is necessary), you should use printf("name is %31s, age is %d", name, age). Then you will get output Colin 23.
You can do it like this:
#include <stdio.h>
int main(void)
{
char name[32];
int age;
printf("Give name and age: ");
scanf("%s%d", name, &age);
printf("%s\n",name);
printf("%d",age);
}