I'm trying to simply read input from the user and store a CD record into some variables. All the variables details are correctly printed out for all the variables except for the second array of char for artist which isn't printing anything. I've tried to deal with the extra character spacing by introducing the space at the front of each of my formatted strings in scanf(), but that hasn't fixed it.
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price);
int main()
{
char title[61];
char artist[41];
short noOfTracks = 0;
int isAlbum = 0;
float price = 0.0;
char albumOrSingleResponse;
printf("Please enter the title: ");
scanf(" %s", title);
printf("Please enter the artist: ");
scanf(" %s", artist);
printf("Please enter the number of records: ");
scanf(" %d", &noOfTracks);
printf("Please enter whether or not the cd is an album/single (A or S): ");
scanf(" %c", &albumOrSingleResponse);
if(albumOrSingleResponse == 'A')
{
isAlbum = 1;
}
printf("Please enter the price of the CD: ");
scanf(" %f", &price);
displayCDInfo(title, artist, noOfTracks, isAlbum, price);
return 0;
}
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price)
{
printf("\nThe title of the CD is %s", title);
printf("\nThe name of the artist is %s", artist);
printf("\nThe number of tracks on this CD are %d", noOfTracks);
printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single");
printf("\nThe price of the cd is $%.2f", price);
}
This will work. Just move the position of char array declaration from top of main body.
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price);
int main()
{
short noOfTracks = 0;
int isAlbum = 0;
float price = 0.0;
char albumOrSingleResponse;
char title[61];
char artist[41];
printf("Please enter the title: ");
scanf(" %s", title);
printf("Please enter the artist: ");
scanf(" %s", artist);
printf("Please enter the number of records: ");
scanf(" %d", &noOfTracks);
printf("Please enter whether or not the cd is an album/single (A or S): ");
scanf(" %c", &albumOrSingleResponse);
if(albumOrSingleResponse == 'A')
{
isAlbum = 1;
}
printf("Please enter the price of the CD: ");
scanf(" %f", &price);
displayCDInfo(title, artist, noOfTracks, isAlbum, price);
return 0;
}
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price)
{
printf("\nThe title of the CD is %s", title);
printf("\nThe name of the artist is %s", artist);
printf("\nThe number of tracks on this CD are %d", noOfTracks);
printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single");
printf("\nThe price of the cd is $%.2f", price);
}
I figured out how to fix this now whilst keeping noOfTracks as a short. Since I was using "%d" for scanf on the Number of tracks variable I was overwriting the space allocated for the previous variable which was artist, hence why it wasn't being displayed. To solve this I had to change the "%d" to "%hu" for short int.
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price);
int main()
{
char title[61];
char artist[41];
short noOfTracks = 0;
int isAlbum = 0;
float price = 0.0;
char albumOrSingleResponse;
printf("Please enter the title: ");
scanf("%s", title);
printf("Please enter the artist: ");
scanf("%s", artist);
printf("Please enter the number of records: ");
scanf("%hu", &noOfTracks);
printf("Please enter whether or not the cd is an album/single (A or S): ");
scanf(" %c", &albumOrSingleResponse);
if(albumOrSingleResponse == 'A')
{
isAlbum = 1;
}
printf("Please enter the price of the CD: ");
scanf(" %f", &price);
displayCDInfo(title, artist, noOfTracks, isAlbum, price);
return 0;
}
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price)
{
printf("\nThe title of the CD is %s", title);
printf("\nThe name of the artist is %s", artist);
printf("\nThe number of tracks on this CD are %hu", noOfTracks);
printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single");
printf("\nThe price of the cd is $%.2f", price);
}
Remove the space: scanf("%s", ...) and add a space: scanf(" %c", ..)
int main()
{
char title[61];
char artist[41];
short noOfTracks = 0;
int isAlbum = 0;
float price = 0.0;
char albumOrSingleResponse;
printf("Please enter the title: ");
scanf("%s", title);
printf("Please enter the artist: ");
scanf("%s", artist);
printf("Please enter the number of records: ");
scanf("%hu", &noOfTracks);
printf("Please enter whether or not the cd is an album/single (A or S): ");
scanf(" %c", &albumOrSingleResponse);
if(albumOrSingleResponse == 'A')
{
isAlbum = 1;
}
printf("Please enter the price of the CD: ");
scanf("%f", &price);
displayCDInfo(title, artist, noOfTracks, isAlbum, price);
return 0;
}
Because when you add a space before " %c" it consumes newline characters entered with previous inputs.
Edit: From this, you may use "%hu" for printing the short to avoid any warning.
Related
I'm practicing C using structs and pointers, I'm asking to the user to input some info using structs and then using pointers to modify it but I'm having problems when I need to get a string with spaces. I switched all the scanfs for fgets and still getting problems with the output.
#include <stdio.h>
#include <stdlib.h>
#define MAXTSTR 25
int main(int argc, char **argv) {
typedef struct birthday {
int day, year;
char month[10];
} BDATE;
struct employee {
char name[MAXTSTR];
int id;
float salary;
BDATE bday;
} emp;
struct employee *ptrEmp = &emp;
printf("Enter employee name:");
fgets(emp.name, MAXTSTR, stdin );
printf("enter id number:");
scanf(" %d", &emp.id);
printf("enter salary");
scanf(" %f", &emp.salary);
printf("enter birhday:");
scanf(" %d", &emp.bday.day);
printf("enter year:");
scanf(" %d", &emp.bday.year);
printf("enter month:");
fgets(emp.bday.month, MAXTSTR, stdin);
printf("\nName: %s \nID: %d \nSalary: %.2f\n", emp.name, emp.id, emp.salary);
printf("%d %s %d", emp.bday.day, emp.bday.month, emp.bday.year);
printf("\n------------------------------------\n");
printf("Enter employee name:");
fgets(ptrEmp->name, MAXTSTR, stdin);
printf("enter id number:");
scanf(" %d", &ptrEmp->id);
printf("enter salary");
scanf(" %f", &ptrEmp->salary);
printf("enter birhday:");
scanf(" %d", &ptrEmp->bday.day);
printf("enter year:");
scanf(" %d", &ptrEmp->bday.year);
printf("enter month:");
scanf(ptrEmp->bday.month, MAXTSTR, stdin);
printf("\nName: %s \nID: %d \nSalary: %.2f\n",
ptrEmp->name, ptrEmp->id, ptrEmp->salary);
printf("%d %s %d", ptrEmp->bday.day, ptrEmp->bday.month,
ptrEmp->bday.year);
return (EXIT_SUCCESS);
}
INPUT and OUTPUT EXAMPLE
Enter employee name:Luis Oliveira
enter id number:01
enter salary1525.25
enter birhday:05
enter year:1991
enter month:
Name: Luis Oliveira
ID: 1
Salary: 1525.25
5
1991
------------------------------------
Enter employee name:Patricia Santos
enter id number:02
enter salary16546.46
enter birhday:05
enter year:1946
enter month:Fev
Name: Patricia Santos
ID: 2
Salary: 16546.46
5
1946
What I'm doing wrong?
Thank you in advance for your help.
Mixing scanf() and fgets() can be very confusing: scanf() leaves the pending newline in the input stream and fgets() reads it and immediately returns because it has reached the end of line.
You can read the month with scanf("%9s", emp.bday.month); and the employee name with scanf(" %14[^\n]", ptrEmp->name);.
Also check for invalid input causing scanf() to return a value different from the expected 1.
Modified program:
#include <stdio.h>
#include <stdlib.h>
#define MAXTSTR 25
typedef struct birthday {
int day, year;
char month[10];
} BDATE;
struct employee {
char name[MAXTSTR];
int id;
float salary;
BDATE bday;
};
int main(int argc, char **argv) {
struct employee emp;
for (int i = 0; i < 2; i++) {
printf("Enter employee name: ");
if (scanf(" %14[^\n]", emp.name) != 1)
return EXIT_FAILURE;
printf("enter id number: ");
if (scanf(" %d", &emp.id) != 1)
return EXIT_FAILURE;
printf("enter salary: ");
if (scanf(" %f", &emp.salary) != 1)
return EXIT_FAILURE;
printf("enter birthday: ");
if (scanf(" %d", &emp.bday.day) != 1)
return EXIT_FAILURE;
printf("enter year: ");
if (scanf(" %d", &emp.bday.year) != 1)
return EXIT_FAILURE;
printf("enter month: ");
if (scanf("%9s", emp.bday.month) != 1)
return EXIT_FAILURE;
printf("\n\nName: %s\nID: %d\nSalary: %.2f\n", emp.name, emp.id, emp.salary);
printf("Birthday: %d %s %d\n", emp.bday.day, emp.bday.month, emp.bday.year);
printf("\n------------------------------------\n");
}
return EXIT_SUCCESS;
}
This question already has answers here:
Why scanf must take the address of operator
(8 answers)
Closed 2 years ago.
Below is my code.
For simplicity I made the code to take the info about 2 friends for now.
But the problem is my for loop in getting user input.
It only works if I remove this part here
printf("Enter Age: ");
scanf("%d", friends[a].age);
here is the full for-loop
for(a=0; a<2; a++) {
printf("Friend no. %d\n", friends[a].fnum+1);
printf("Enter Name: ");
gets(friends[a].name);
printf("Enter Town: ");
scanf("%s", friends[a].address);
printf("Enter Age: ");
scanf(" %d", friends[a].age);
printf("Enter Course: ");
scanf(" %s", friends[a].course);
printf("Favorite foods! \n");
printf("Dish:");
scanf(" %s", friends[a].fav_dish);
printf("Snack:");
scanf(" %s", friends[a].fav_snack);
printf("Drink:");
scanf(" %s", friends[a].fav_drink);
printf("\n");
}
At first, I thought it was the age part was the problem, so I brought it last. But it did not solve it.
I thought it was the scanf too, so I added a space in scanf(" %s", friends[a].course); But nothing work.
I also tried this
printf("Enter Age: ");
scanf(" %d\n ", friends[a].age);
so I tried deleting
printf("Enter Age: ");
scanf("%d", friends[a].age);
and the loop continued to friend 2
What should I do?
Here is my full source code:
#include <string.h>
struct myFriends {
char name[30];
char address[20];
int age;
char course[20];
char fav_dish[20], fav_snack[20], fav_drink[20];
}; struct myFriends friends[2];
int main () {
int a;
puts("Please enter the following info for 2 friends");
for(a=0; a<2; a++) {
printf("Friend no. %d\n", a+1);
printf("Enter Name: ");
scanf("%s", friends[a].name);
printf("Enter Town: ");
scanf("%s", friends[a].address);
printf("Enter Age: ");
scanf(" %d\n ", friends[a].age);
printf("Enter Course: ");
scanf(" %s", friends[a].course);
printf("Favorite foods! \n");
printf("Dish:");
scanf(" %s", friends[a].fav_dish);
printf("Snack:");
scanf(" %s", friends[a].fav_snack);
printf("Drink:");
scanf(" %s", friends[a].fav_drink);
printf("\n");
}
printf("Here are the details");
for (a=0; a<2; a++) {
printf("\n\n Friend no. %d", a+1);
printf("Name:");
puts(friends[a].name);
printf("Town: ");
puts(friends[a].address);
printf("Age: ");
printf("%d", friends[a].age);
printf("Fave FOODS!: ");
puts(friends[a].fav_dish);
puts(friends[a].fav_snack);
puts(friends[a].fav_drink);
}
return 0;
}
In here, I add & mark to pass pointers to scanf, so try this. I hope this works for you.
#include
#include <stdio.h>
#include <string.h>
struct myFriends {
char name[30];
char address[20];
int age;
char course[20];
char fav_dish[20], fav_snack[20], fav_drink[20];
}; struct myFriends friends[2];
int main () {
int a;
puts("Please enter the following info for 2 friends");
for(a=0; a<2; a++) {
char name[30];
char address[20];
int age;
char course[20];
char fav_dish[20], fav_snack[20], fav_drink[20]
printf("Friend no. %d\n", a+1);
printf("Enter Name: ");
scanf("%s", &name);
friends[a].name=name;
printf("Enter Town: ");
scanf("%s", &address);
friends[a].address=address;
printf("Enter Age: ");
scanf(" %d\n ", &age);
friends[a].age=age;
printf("Enter Course: ");
scanf(" %s", &course);
friends[a].course=course;
printf("Favorite foods! \n");
printf("Dish:");
scanf(" %s", &fav_dish);
friends[a].fav_dish=fav_dish;
printf("Snack:");
scanf(" %s", &fav_snack);
friends[a].fav_snack=fav_snack;
printf("Drink:");
scanf(" %s", &fav_drink);
friends[a].fav_drink=fav_drink;
printf("\n");
}
printf("Here are the details");
for (a=0; a<2; a++) {
printf("\n\n Friend no. %d", a+1);
printf("Name:");
puts(friends[a].name);
printf("Town: ");
puts(friends[a].address);
printf("Age: ");
printf("%d", friends[a].age);
printf("Fave FOODS!: ");
puts(friends[a].fav_dish);
puts(friends[a].fav_snack);
puts(friends[a].fav_drink);
}
return 0;
}
I have to write a program in C for a school project that registers a geriatric client, this is my code:
int position=0, correctData=0, day, month, year, phone, iRS, exercises;
float height, weight;
char confirmation, name[100], address[100], numberToCheck[9];
for(int i=0; Client[i]->name!="NULL";i++){
position++;
if(i==30){
break;
}
}
do{
fflush(stdin);
system("cls");
printf("\n\tINSERT NEW CLIENT");
printf("\nInsert client name: ");
gets(name);
printf("\nInsert client address: ");
gets(address);
printf("\nInsert client birthday(dd/mm/yyyy): ");
scanf("%d/%d/%d", &day,&month,&year);
do{
fflush(stdin);
strcpy(numberToCheck, "");
printf("\nInsert client phone number: ");
gets(numberToCheck); //THIS IS THE LINE ERASING MY ADDRESS VARIABLE
if(isPhone(numberToCheck)==0){
printf("\nNumber not valid");
}
}while(phone(numberToCheck)==0);
phone= validateInput(numberToChek);
do{
fflush(stdin);
strcpy(numberToCheck, "");
printf("\nInsert client tax number: ");
gets(numberToCheck);
if(isIRS(numberToCheck)==0){
printf("\nNumber not valid");
}
}while(isIRS(numberTocheck)==0);
iRS= validateInput(numberToCheck);
printf("\nInsert client height: ");
scanf("%f", &height);
printf("\nInsert client weight: ");
scanf("%f", &weight);
printf("\nInsert the number of exercises made: ");
scanf("%d", &exercise);
fflush(stdin);
system("cls");
printf("Name : %s", name);
printf("\nAddress : %s", address);
printf("\nBirthday : %02d/%02d/%04d", dia, mes, ano);
printf("\nPhone number : %d", telefone);
printf("\IRS : %d", contribuinte);
printf("\nHeight and Weight : %.2fm e %.2fKg", height, weight);
printf("\nNumber of exercises : %d", exercise);
printf("\n\nIs the data correct??(Y/N): ");
scanf("%c", &confirmation);
if(confirmation=='Y' || confirmation=='y'){
strcpy(Client[position]->name, name);
strcpy(Client[position]->address, address);
Client[position]->dayBirth = day;
Client[position]->monthBirth = month;
Client[position]->yearBirth = year;
Client[position]->phone = phone;
Client[position]->iRS = iRS;
Client[position]->height= height;
Client[position]->weight= weight;
Client[position]->exercise = exercise;
correctData = 1;
}
}while(correctData==0);
printf("\nUser registered");
printf("\n\nPress Enter to continue");
system("pause >nul /nobreak");
I receive by reference the array Client[100] so that i can modify its elements.
In the part of the code to check if it's a phone number/iRS number i use a pre-coded submodule to validate it.
The problem I'm having with the code is that it stores the address of the client but when the program receives the numberToCheck to check if it is a phone number the address variable is cleaned, becomes empty and I don't see why.
I appreciate any help and time given to help me solve the problem
I just ended up writing these codes. It is a structure of data which is supposed to be written in the FILE. I want all the strings to be entered by the user with spaces in between.
I used fgets(), but fgets() produces a newline in the time of reading the file. Any way to do it? And please explain if any buffer overflow occurs. Thank you.
#include <stdio.h>
FILE *student_records;
struct studentdetails{
char name[20];
int age;
int class_room;
char section[10];
char fathername[20];
char mothername[20];
}totalstudentdetails;
struct studentmarks{
int physics;
int chemistry;
int maths;
int biology;
int english;
}totalstudentmarks;
int main()
{
student_records=fopen("studentrec.dat","a+");
printf("\n ADD STUDENT RECORDS \n\n\n");
printf(" Enter Student Name > ");
scanf("%s",totalstudentdetails.name);
printf(" Enter Student Age > ");
scanf("%d", &totalstudentdetails.age);
getchar();
printf(" Enter Student Class > ");
scanf("%d", &totalstudentdetails.class_room);
getchar();
printf(" Enter Student Section > ");
scanf("%s", totalstudentdetails.section);
printf("Enter Student Father's Name > ");
scanf("%s",totalstudentdetails.fathername);
getchar();
printf("Enter Student mother's Name > ");
scanf("%s",totalstudentdetails.mothername);
getchar();
fwrite(&totalstudentdetails, sizeof(totalstudentdetails), 1, student_records);
/* Student marks details */
printf("\n\n\n\n");
printf(" Marks Obtained(Out Of 100) \n\n");
printf(" Enter Mark In Physics > ");
scanf("%d", &totalstudentmarks.physics);
getchar();
printf(" Enter Mark In Chemistry > ");
scanf("%d", &totalstudentmarks.chemistry);
getchar();
printf(" Enter Mark In Maths > ");
scanf("%d", &totalstudentmarks.maths);
getchar();
printf(" Enter Mark In Biology > ");
scanf("%d", &totalstudentmarks.biology);
getchar();
printf(" Enter Mark In English > ");
scanf("%d", &totalstudentmarks.english);
getchar();
fwrite(&totalstudentmarks, sizeof(totalstudentmarks), 1, student_records);
/* closing file */
fclose(student_records);
}
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.