Can anyone advise why values are not getting stored in struct array?
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
This is what I tried:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int menu(void);
struct item
{
int i_SKU;
int i_QUANTITY;
int i_PRICE;
};
int main()
{
int i,j = 0;;
int n;
int input;
//struct item item1[10] = { {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0} };
struct item item1[]={0};
struct item buff[]={0};
//printf("size of %d", sizeof(item1)/sizeof(item1[0]));
printf("Welcome to the Inventory\n");
printf("===================\n");
B: printf("Please select from the following:\n");
A: menu();
scanf("%d", &input);
switch (input)
{
case 1:
printf("Inventory\n");
printf("=========================================\n");
printf("ku Price Quant\n");
for (i = 0; i < sizeof(buff)/sizeof(buff[0]); i++)
{
printf("%d %d %d\n", buff[i].i_SKU, buff[i].i_PRICE, buff[i].i_QUANTITY);
}
printf("=========================================\n");
goto B;
case 2:
//n = sizeof(item1)/sizeof(item1[0]) + 1;
//for (i=n; i < ; i++)
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
printf("Quantity:");
buff[j].i_QUANTITY=scanf("%d", &item1[j].i_QUANTITY);
printf("Price:");
buff[j].i_PRICE=scanf("%d", &item1[j].i_PRICE);
printf("The item added.\n");
j=j+1;
goto B;
case 0:
printf("bye!");
exit(1);
default:
printf("Invalid input, try again:\n");
goto A;
}
return 0;
}
int menu(void)
{
printf("1) Display.\n");
printf("2) Add to inventory.\n");
printf("0) Leave.\n");
printf("Select:");
return 0;
}
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
scanf doesn't return the value it reads, it returns the number of characters it reads.
So these lines:
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
buff[j].i_SKU=scanf("%d", &item1[j].i_QUANTITY);
buff[j].i_SKU=scanf("%d", &item1[j].i_PRICE);
don't do what you want. They put the integer into item1[j].i_X, but assign buff[j].i_X to the number of characters read.
Also, I'm guessing you intended the left hand side of those three equations to differ, not all refer to i_SKU.
Another possible problem: your buffers don't have a length specified, so they will probably just have storage for one element.
EDIT:
I'm not sure what purpose the items1 array serves in your code, but if you want the value in both arrays, you can try the following:
int sku;
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &sku);
item1[j].i_SKU = sku;
buff[j].i_SKU = sku;
// etc.
Related
I am trying to make a program where the user inserts the price of a certain item of his choice, then that price is stored in a list, and the user can expand that last as he wishes, but there is a problem, even though I have the exact same arguments and parameters, the array "prices" is considered to be a pointer for some reason.
#include <stdio.h>
void ask(char ques, int index, double prices[index], double price)
{
printf("Do you want to expand your list y/n: ");
scanf("%c", &ques);
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
switch (ques)
{
case 'y':
prices[index + 1] = price;
case 'n':
main();
}
}
int main()
{
int index = -1;
double prices[index];
double price;
char ques;
ask(ques, index, prices[index], price);
}
I have this error: argument of type "double" is incompatible with parameter of type "double *"C
A solution using an array on the stack to store the prices.
prices.c
#include <stdio.h>
void ask(double prices[], int *elements, int max_elements)
{
if (*elements >= max_elements) {
printf("List is already full. (%d elements)\n", *elements);
return;
}
while (*elements < max_elements) // as long as there is space left
{
double price;
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
prices[*elements] = price; // store price in array
*elements += 1; // increase number of elements
if (*elements == max_elements) {
printf("List is full. (%d elements)\n", max_elements);
break; // leave loop
}
char ques;
printf("Do you want to expand your list (y/n): ");
scanf(" %c", &ques);
if (ques == 'n') {
break; // leave loop
}
}
}
int main()
{
const int MAX_ELEMENTS = 10000; // 10000 prices should be enough for now
double prices[MAX_ELEMENTS]; // array to store 10000 prices
int elements = 0; // number of prices, currently none
ask(prices, &elements, MAX_ELEMENTS); // let user fill it
for (int i = 0; i < elements; i++) {
printf("%3d: %.2lf\n", i + 1, prices[i]); // print price number and price
}
return 0; // return 0 to indicate no error
}
Let's see how it works so far:
$ gcc -Wall prices.c
$ ./a.out
What do you want the price of the next item to be: 1.11
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 2.22
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 101
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 1000000.99
Do you want to expand your list (y/n): n
1: 1.11
2: 2.22
3: 101.00
4: 1000000.99
$
Test it online: https://onlinegdb.com/x1jVUU6GT
My Helper Function, getInput() will read the data into the array list until end of input, where they will read in the Staff ID, total number of leave allowed and the number of days of leave taken so far. It is supposed to return the number of records read through the pointer variable n. However, when I try to dereference the pointer, the program will close and I am not sure why. Thank you in advance
My Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 80
typedef struct {
int id; /* staff identifier */
int totalLeave; /* the total number of days of leave allowed */
int leaveTaken; /* the number of days of leave taken so far */
}leaveRecord;
// Function Prototypes
void getInput(leaveRecord list[ ], int *n);
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n);
void printList(leaveRecord list[ ], int n);
int main(){
int choice, ID, LEAVE, leaveApproval;
int recordsRead = 0;
int *ptr = recordsRead;
leaveRecord list[SIZE];
do{
printf("Please Select one of the following Options:\n");
printf("1: getInput()\n");
printf("2: mayTakeLeave()\n");
printf("3: printList()\n");
printf("4: Quit!!\n");
scanf("%d", &choice);
switch(choice){
case 1:
getInput(list, recordsRead);
printf("Temp is %d", recordsRead);
break;
case 2:
printf("Please Enter the Staff ID:\n");
scanf("%d", &ID);
printf("Please Enter the Number of Days of Leave:\n");
scanf("%d", &LEAVE);
leaveApproval = mayTakeLeave(list,ID,LEAVE, ptr);
switch(leaveApproval){
case -1:
printf("Error!! Staff Member not found!");
break;
case 0:
printf("Leave is not approved");
break;
case 1:
printf("Leave is approved");
break;
}
break;
case 3:
break;
}
}while (choice < 3);
return 0;
}
void getInput(leaveRecord list[ ], int *n){
int option = 0, temp = 0;
int userInput;
while (option == 0){
printf("Please key in the Staff Identifier:\n");
scanf("%d", &list->id);
printf("Please key in the Total Number of Days allowed:\n");
scanf("%d", &list->totalLeave);
printf("Please key in the Number of Days of Leave taken:\n");
scanf("%d", &list->leaveTaken);
printf("Please Key in 1 if you like to stop adding Records:\n");
scanf("%d", &userInput);
if(userInput == 1){
break;
}
temp += 1;
}
// Why does dereferencing a Pointer Variable kill the entire program?
*n = temp;
}
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n){
int leaveUsed = (leave + list->leaveTaken);
for(int i = 0; i < n; i += 1){
if(list->id == id){
if((leaveUsed < list->totalLeave) || (leaveUsed == list->totalLeave)){
return 1;
}
else{
return 0;
}
}
else{
return -1;
}
}
}
void printList(leaveRecord list[ ], int n){
for(int i = 0; i < n; i += 1){
printf(list);
}
}
void getInput(leaveRecord list[ ], int *n);
Here, In getInput function n is an integer type pointer variable which wants address of integer variable.
But here, getInput(list, recordsRead) you are just sending value of records read.
You have to send address of recordsRead.
getInput(list, &recordsRead)
Also in function printList you are using wrong syntax.
printf(list);
Do this :
printf("%d",list[i]);
or
printf("%d",*(list+i));
I have this silly program with my silly problem. I am a very beginner. Let me tell you what I want to do and what is happening here:
What I want to do: I am basically trying to make a function for input which is named here as inp(). This function will ask for input using these two lines:
printf("Enter the Number: ");
scanf("%d", &dip);
When my program will get the number from the user, it will store that inside a variable, let's say dip and will use this number in our another two functions named squarefn and cubefn. I don't know what's going wrong here. But, I can't use the inp() properly to get the number from user.
Why I want to use the inp() function?: Basically, I just want to keep everything inside each function so whenever I need, I will just call my functions. I created inp() so that, I don't need to ask twice or type twice for input.
**What is the output?: ** It's showing some random value or trash value.
Need more information? Feel free to ask!
#include<stdio.h>
int squarefn(int x);
int cubefn(int cube);
int coic();
int printkor(int printkortesi);
int inp();
int main()
{
coic();
}
int squarefn(int input)
{
input = input * input;
return input;
}
int cubefn(int input)
{
input = input * input * input;
return input;
}
int coic()
{
int coi;
int x;
printf("Which one you want?\n");
printf("1. Square\n");
printf("2. Cube\n");
printf("Enter here: ");
scanf("%d", &coi);
int cubed = cubefn(x);
switch (coi)
{
case 1:
// printf("Enter the Number: ");
// scanf("%d", &x);
inp();
int dear = inp(x);
squarefn(dear);
int squared = squarefn(x);
printkor(squared);
break;
case 2:
printf("Enter the Number: ");
scanf("%d", &x);
cubefn(x);
int cubed = cubefn(x);
printkor(cubed);
break;
default:
printf("Error.");
break;
}
}
int inp()
{
int dip;
printf("Enter the Number: ");
scanf("%d", &dip);
return dip;
}
int printkor(int printkortesi)
{
printf("Printed: %d", printkortesi);
}
There is a lot of redundant code in your program, many of the statements don't do anything except taking CPU time . Read about Function Calls in C. Most of your doubts will be solved after a good read
return_type function_name( parameter list ) {
body of the function
}
You have return type of int, to receive value of function foo
int foo(int x)
{return x*x;}
int main()
{
int y =foo(5); //integer y takes value returned by function foo, that is 5
printf("%d\n",y); // This will print value 25
return 0;
}
Your code altered as below, should work now:
#include<stdio.h>
int squarefn(int x);
int cubefn(int cube);
int coic();
int printkor(int printkortesi);
int inp();
int main()
{
coic();
}
int squarefn(int input)
{
input = input * input;
return input;
}
int cubefn(int input)
{
input = input * input * input;
return input;
}
int coic()
{
int coi;
int x;
printf("Which one you want?\n");
printf("1. Square\n");
printf("2. Cube\n");
printf("Enter here: ");
scanf("%d", &coi);
int cubed = cubefn(x);
int dear = inp();
switch (coi)
{
case 1:
{int squared = squarefn(dear);
printkor(squared);
break;}
case 2:
{int cubed = cubefn(dear);
printkor(cubed);
break;}
default:
printf("Error.");
break;
}
}
int inp()
{
int dip;
printf("Enter the Number: ");
scanf("%d", &dip);
return dip;
}
int printkor(int printkortesi)
{
printf("Printed: %d\n", printkortesi);
}
Edit:
Fixed it, I just noticed there was variable declaration in the switch statement. Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. So I added { } in switch and it should work now.
how to do we declare parallel arrays in C. And also , how to add more than one data type in a single array. for example, i want to declare int and char data type in the same array
#include <stdio.h>
int main()
double linetotal= qty*price;
printf("line total =%lf\n",linetotal);
double subtotal = line total - discount ;
}
}
Check the solution now.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM_CODE 10
const char *CODE[NUM_CODE] = {"B100","B122","B134","B138","B145","B160","B165","B178","B186","B194"};
double PRICE[NUM_CODE]={12.8,18.7,20.5,11.5,25.5,20.55,25.65,14.85,22.2,24.25};
int main()
{
char name[20];
printf("Enter buyer name: ");
scanf("%s",name);
int entry;
printf("Enter number of entries for the invoice: ");
scanf("%d",&entry);
char code[10];
int quantity;
double price,linetotal=0;
int i;
for(i=1;i<=entry;i++)
{
printf("Enter Code: ");
scanf("%s",code);
printf("Enter Quantity: ");
scanf("%d",&quantity);
printf("Enter Unit Price: ");
scanf("%lf",&price);
int j;
int flag=0;
for(j=1;j<=NUM_CODE;j++){
// how do i print values like B100 without getting errors//
printf("%s ",CODE[j-1]);
// how to match the user input with parallel arrays?//
if(strcmp(CODE[j-1],code)==0 && PRICE[j-1]==price){
//If correct code and price found do
printf("\nValid Code and price found\n");
//set the flag and break from the loop
flag=1;
break;
}
}
if(flag==0){
//Exit the program with invalid entry
printf("\nInvalid Code and price found\n");
printf("The program will close now...\n");
exit(1);
}
// how do calculate line total,and subtotal after discount//
// discount is 10% if line total is greater than Rs5000//
linetotal = price * quantity + linetotal;
printf("\n");
}
double subtotal;
if(linetotal>5000){
subtotal = 0.9*linetotal;
}
else if(linetotal>=1000 && linetotal<=5000){
subtotal = 0.95*linetotal;
}
else{
subtotal = linetotal;
}
printf("Discount: %0.2lf%%\nTotal Price: %lf\n",((linetotal-subtotal)/linetotal)*100,subtotal);
return 0;
}
I cooked a code for a program that asks the user to fill in information about a person (ReadDate/ReadPerson), then it asks for the range of people the user wants to print, and the function prints these people. (PrintRange)
I don't understand why the program is not working; it's stuck on the point when it should print the person... it's means there is probably a problem in either PrintPerson or PrintDate, or in the way I am calling these functions.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int day, month, year;
} Date;
typedef struct{
char *first_name, *last_name;
int id;
Date birthday;
} Person;
void ReadDate(Date *a)
{
printf("Enter the day: ");
scanf("%d", &a->day);
printf("Enter the month (1-12): ");
scanf("%d", &a->month);
printf("Enter the year: ");
scanf("%d", &a->year);
}
void ReadPerson(Person *b)
{
char temp_first_name[21];
char temp_last_name[21];
printf("Enter the first name: ");
gets(temp_first_name);
b->first_name = (char*)malloc(strlen(temp_first_name)+1);
strcpy(b->first_name,temp_first_name);
//need to check malloc (later)
printf("Enter the last name: ");
gets(temp_last_name);
b->last_name = (char*)malloc(strlen(temp_last_name)+1);
strcpy(b->last_name, temp_last_name);
//need to check malloc (later)
printf("Enter the id number: ");
scanf("%d",&b->id);
printf("Enter the birthday:\n");
ReadDate(&b->birthday);
}
int ReadAllDate (Person *b)
{
//Person* b;
int count=1;
char choice;
printf("Would you like to enter a person?(y,n)\n");
choice = getchar();
while(choice == 'y')
{
b = (Person*)malloc(1 * sizeof(Person));
getchar();
ReadPerson(b);
printf("Done!\n");
count++;
getchar();
printf("Would you like to add a person?(y,n)\n");
choice = getchar();
}
count--;
printf("The number of entered persons is %d\nBye\n", count);
return count;
}
void PrintPerson(Person b)
{
printf("%s %s %d\n", b.first_name, b.last_name, b.id);
}
void PrintDate(Date a)
{
printf("%d // %d // %d\n",a.day,a.month,a.year);
}
void PrintRange(Person *b,int count,int ind1,int ind2)
{
int i;
if (ind1<0 || ind1>ind2 || ind2>count)
{
printf("error! you slip out from the limits of the array.\n");
}
else
{
for (i=ind1; i<=ind2; i++)
{
PrintPerson(*(b+i));
PrintDate((b+i)->birthday);
}
}
}
int main(int argc, const char * argv[])
{
Person* b;
int count;
int ind1, ind2;
count = ReadAllDate(b);
printf("insert the first index (the smaller): ");
scanf("%d", &ind1);
printf("insert the second index (the bigger): ");
scanf("%d", &ind2);
PrintRange(b, count, ind1, ind2);
}
The problem is that nowhere you are actually creating an array of Person objects. The function ReadAllDate() never changes the value of the variable b in main(). Instead, for every person you read in, it allocates memory for it, and stores the pointer to that Person in the local variable b in ReadAllDate(). Every time it does it, it forgets the previous value of b.
In main(), the value of b is unitinialized all the time. When you are trying to print persons, it will most likely crash or print garbage.
I see other issues with your code:
Don't use gets(), always use fgets(). The former can write past the end of the buffer you are providing.
Don't do malloc(strlen(...))+strcpy(), use strdup().
Start with count = 0, that way you don't need the count-- in ReadAllDate(). As a computer programmer, it's best to count from zero instead of one.
Write b[i] instead of *(b+i), and b[i].birthday instead of (b+i)->birthday.