my program fails when I build and succeeds when I rebuild? - c

Whenever I build my program using visual studio 2015, it says it fails, but when I rebuild immediately after, it says it succeeded. Another question is how do i store multiple inputs for SKU, price and price and then properly output it.
#include <stdio.h>
#define MAX_ITEMS 10
struct Item
{
int sku_[10];
int quantity_[10];
float price_[10];
};
int main(void)
{
int size = 0;
int input =1;
int i;
int j;
struct Item items[10];
printf("Welcome to the Shop\n");
printf("===================\n");
printf("Please select from the following options\n");
while (size <= MAX_ITEMS && input != 0)
{
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n);
printf("Select:");
scanf_s("%d", &input);
while (input < 0 || input >2 && input != 0)
{
printf("Invalid input, try again: Please select from the following);
printf("1)Display the inventory.\n2)Add to the inventory.\n0) Exit.\n");
printf("Select:");
scanf_s("%d", &input);
}
if (input == 1)
{
printf("Inventory\n");
printf("====================\n");
printf("Sku Price Quantity\n");
printf("%d", items[size].sku_);
}
else if (input == 2)
{
printf("Please input a SKU number:");
if (size >= MAX_ITEMS)
{
printf("The inventory is full");
}
else if (size < MAX_ITEMS)
{
scanf_s("%d", &items[size].sku_);
printf("Quantity:");
scanf("%d", &items[size].quantity_);
printf("Price:");
scanf("%f", &items[size].price_);
printf("The item is successfully added to the inventory.\n");
size += 1;
}
}
else if (input == 0)
{
printf("Good bye");
}
}
}

Here are errors detected in the source code:
1- As WhozCraig suggests, two printf() calls are bad terminated.
Instead of:
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n);
...
printf("Invalid input, try again: Please select from the following);
Add a text terminator:
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n");
...
printf("Invalid input, try again: Please select from the following");
2- When entering items[size].sku_, or .quantity_, or .price_, use a pointer to a value instead of a pointer to a array of value. The struct Item is malformed.
Just modify the struct Item:
struct Item
{
int sku_; // unexpected use [10];
int quantity_; // unexpected use [10];
float price_; // unexpected use [10];
};
3- When printing the inventory, use a loop and not the last index. And format all attributes of each items[i] to align with the header.
printf("Sku Price Quantity\n");
for(i=0;i<size;i++) {
printf("%6d %8d %6.2f\n", items[i].sku_,items[i].quantity_,items[i].price_);
}

Related

Beginner in C: Can't properly printf first and last element in double array?

I'm trying to display a Wish List on the command line. The user enters the cost of the item, the level of priority (1-3), and whether or not it has financing options (y/n). The inputted values are put in multiple arrays. After the user enters all their values, they're displayed in a table at the end.
Everything in my code works fine except when I try to printf the user inputed cost values (double itemCosts[numOfItems];) in the table. The first and last element don't print properly, even when I input the same price (6225.88) for all of them. The last element is just 0.000000. See included pic of table output.
I tried debugging the issue by separating the cost-related loops and compiling/running them as another file and the costs display correctly...so I'm thinking the bug is somewhere else, but I can't find it.
#define MAX_ITEMS 10
#include <stdio.h>
int main()
{
const double MIN_INCOME = 500, MAX_INCOME = 400000;
int numOfItems;
double netIncome, itemTotal;
double itemCosts[numOfItems];
int itemPriors[numOfItems];
char itemFinOps[numOfItems];
printf("+--------------------------+\n");
printf("+ Wish List Forecaster |\n");
printf("+--------------------------+\n\n");
// Prompt for net monthly income
do
{
printf("Enter your monthly NET income: $");
scanf("%lf", &netIncome);
if (netIncome < MIN_INCOME)
{
printf("ERROR: You must have a consistent monthly income of at least $500.00\n\n");
}
else if (netIncome > MAX_INCOME)
{
printf("ERROR: Liar! I'll believe you if you enter a value no more than $400000.00\n\n");
}
} while (!(netIncome >= MIN_INCOME && netIncome <= MAX_INCOME));
printf("\n");
// Prompt for # of wish list items
do
{
printf("How many wish list items do you want to forecast?: ");
scanf("%d", &numOfItems);
if (!(numOfItems > 0 && numOfItems <= MAX_ITEMS))
{
printf("ERROR: List is restricted to between 1 and 10 items.\n\n");
}
printf("\n");
} while (!(numOfItems > 0 && numOfItems <= MAX_ITEMS));
// Store wish list item details
for (int i = 0; i < numOfItems; i++)
{
printf("Item-%d Details:\n", i + 1);
do //////////////// ******** PROMPT COST ********** //////////
{
printf("Item cost: $");
scanf("%lf", &itemCosts[i]);
if (!(itemCosts[i] >= (double)100))
{
printf(" ERROR: Cost must be at least $100.00\n");
}
} while (!(itemCosts[i] >= (double)100));
do // prompt priority
{
printf("How important is it to you? [1=must have, 2=important, 3=want]: ");
scanf("%d", &itemPriors[i]);
if (!(itemPriors[i] >= 1 && itemPriors[i] <= 3))
{
printf(" ERROR: Value must be between 1 and 3\n");
}
} while (!(itemPriors[i] >= 1 && itemPriors[i] <= 3));
do // prompt finance options
{
printf("Does this item have financing options? [y/n]: ");
scanf(" %c", &itemFinOps[i]);
if (!(itemFinOps[i] == 'y' || itemFinOps[i] == 'n'))
{
printf(" ERROR: Must be a lowercase 'y' or 'n'\n");
}
} while (!(itemFinOps[i] == 'y' || itemFinOps[i] == 'n'));
printf("\n");
}
///////// display summary of item details in TABLE //////////
printf("Item Priority Financed Cost\n");
printf("---- -------- -------- -----------\n");
for (int j = 0; j < numOfItems; j++)
{
printf(" %d %d %c %lf\n", j + 1, itemPriors[j], itemFinOps[j], itemCosts[j]);
itemTotal += itemCosts[j];
}
return 0;
}
int numOfItems;
double netIncome, itemTotal;
double itemCosts[numOfItems];
int itemPriors[numOfItems];
char itemFinOps[numOfItems];
It is undefined behaviour as your numOfItems is not inilized. In C table will not grow or shrink to the size when you change this variable
Change to:
double itemCosts[MAX_ITEMS];
int itemPriors[MAX_ITEM];
char itemFinOps[MAX_ITEM];
Always check the result of scanf. Exmaple:
if(scanf("%lf", &netIncome) != 1){ /* handle error*/}
As Vlad from Moscow and 0___________ said, you cannot define an array using a not initialised variable for the number of its elements. You can define the variables as
double *itemCosts;
int *itemPriors;
char *itemFinOps;
and after the variable numOfItems is given a value, you dynamically allocate memory as follows:
itemCosts = (double*) malloc(numOfItems * sizeof(double));
itemPriors = (int*) malloc(numOfItems * sizeof(int));
itemFinOps = (char*) malloc(numOfItems * sizeof(char));
or
itemCosts = (double*) calloc(numOfItems, sizeof(double));
itemPriors = (int*) calloc(numOfItems, sizeof(int));
itemFinOps = (char*) calloc(numOfItems, sizeof(char));
calloc initialises all elements of array to 0
At the end you must free the allocated memory:
free(itemCosts);
free(itemPriors);
free(itemFinOps);

Read values into an array fails

I want to use a function to scanf up to 10 values for an array with the size 10, and also keep track of the number of values that are in the array because I'll need it later for solving some maths about the array, (max value, min value, etc.).
#include <stdio.h>
int enter(int MeasurmentData[], int nrOfmeasurments)
{
for(int i=0;i<10;++i)
{
int MeasurmentData[10];
scanf("%d",&MeasurmentData[i]);
int nrOfmeasurments = 0;
nrOfmeasurments ++;
return nrOfmeasurments;
}
int main()
{
int MeasurmentData[10];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n");
printf("v (View)\n");
printf("e (Enter)\n");
printf("c (Compute)\n");
printf("r (Reset)\n");
printf("q (Quit)\n");
printf("enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') \\ enter values
{
int MeasurmentData[10];
int nrOfmeasurments;
enter(MeasurmentData, nrOfmeasurments);
}
else if(menuoption == 'v') \\\ view values
{
//printf("%d", MeasurmentData[]);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
return 0;
}
}
}
When I run the program it should print Measurment tool 2.0, after the the user has the choice of inputting e(enter) which will scan in up to 10 values into an array, if the user clicks q(quit) while in the enter option already he will be returned to the main menu where he can do whatever.
V(view) prints out the array for the user so that he can view what elements are inside.
C(compute) uses the elements inside and the nr of elements to calculate the highest value element, lowest.
There are some errors in your code. Ill try to explain. You have over declared your variables too many times. And since you have a fixed loop you don't need to count the measurements you will always read 10 measurements.
Below are the code with some modifications. Feel free to ask anything about it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXIMUM_MEASURMENT 10
int enter(int MeasurmentData[])
{
char input[100];
int nrMeasurement = 0;
// reseting Measurment data
for(int i=0;i<MAXIMUM_MEASURMENT;++i) MeasurmentData[i] = 0;
for(int i=0;i<MAXIMUM_MEASURMENT;++i)
{
scanf("%99s", input);
if(strcmp(input, "q") == 0) {
break;
}
MeasurmentData[i] = (int) strtol(input, (char **)NULL, 10);
nrMeasurement++;
}
return nrMeasurement;
}
void showMeasurments(int* MeasurmentData, int length) {
int i = 0;
printf(" ======== Measurment ======== \n");
for(i = 0; i < length; i++) {
printf("%d ", MeasurmentData[i]);
}
printf("\n");
}
int main()
{
int MeasurmentData[MAXIMUM_MEASURMENT];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n" "v (View)\n" "e (Enter)\n" "c (Compute)\n" "r (Reset)\n" "q (Quit)\n enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') // enter values
{
enter(MeasurmentData);
}
else if(menuoption == 'v') // view values
{
// show
showMeasurments(MeasurmentData, MAXIMUM_MEASURMENT);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
return 0;
}
Edit: i have updated the code. So i have read the comments of your question and there you have explained a little better what you are trying to accomplish. So since you have the requirement to press 'q' to stop reading values. I have to read all measurments as string and convert to integer if it is not the character q.
Edit 2: Thanks to #user3629249 to point out some of the flaws from the code ill update with his suggestions.

Function Crashes Main After Finishing Execution - C

I made this simple program that asks the user to input the number of columns the matrix called arp is going to have because, that way when the program asks the user to input a number so it can find matches on the numbers stored at the array without comparing all 10 columns allocated on memory with array to pointer type.
The problem here comes when the user inputs into the columns size definition 2. All works fine before the last function of p3() does its job, then it doesn't even return to main to execute the infinite loop defined there. I have tried removing the pointers and didn't work; I also tried removing other parts of the code but still nothing...
Update: Tried removing the function to find elements felmnt() and still the same.
Here is The Buggy Code:
#include <stdio.h>
#include <stdlib.h>
int loop = 1;
void keepalive(void)
{
int ckr = 0;
fflush(stdin);
printf("\n\n ******[s]<< CONTINUE | EXIT >>[n]******\n");
while(printf(" > ") && (ckr = getchar()) != 's' && ckr != 'n') fflush(stdin);
getchar();
if(ckr == 'n') loop = 0;
system("CLS");
}
void felmnt(int *colu, int (*arp)[10])
{
int nius=0, colmts, x, i, ejct;
do
{ // loop to let the user find more elements inside matrix
colmts=0;
printf("\n Insert The Number To Find\n > ");
scanf("%d", &nius);
for(x=0; x<*colu; x++) // search of element inside matrix
{
for(i=0; i<=9; i++)
if(nius == arp[i][x])
colmts++;
}
if(colmts>1) // results printing
{
printf("\n %d Elements Found", colmts);
}else if(colmts)
{
printf("\n 1 Element Found");
}else
{
printf("\n Not Found");
}
printf("\n TRY AGAIN? s/n\n > ");
ejct=getchar();
getchar();
}while(ejct=='s');
}
void mat(int *colu, int (*arp)[10])
{
int ci, cn, tst=0;
for(ci=0; ci<*colu; ci++)
{
for(cn=0; cn<10; cn++)
{
printf("\n Input The Number [%d][%d]\n > ", ci+1, cn+1);
scanf(" %d", &arp[cn][ci]);
}
}
printf(" Numbers Inside Matrix> ");
for(ci = 0; ci<*colu; ci++)
{
for(cn=0; cn<10; cn++) printf(" %d", arp[cn][ci]);
}
}
void p3(void)
{ // >>>>main<<<<
int colu=0;
while(loop)
{
printf("\n Input The Quantity Of Columns To Use\n > ");
scanf("%d", &colu);
int arp[10][colu];
mat(&colu, arp);
felmnt(&colu, arp);
keepalive();
}
}
int main(void)
{
int ck = 0, ndx;
while(1)
{ // infinite loop
p3();
fflush(stdin);
printf("\nPause !!!");
getchar();
}
return 0;
}

Structure C: Storing values in an array

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.

C programming: Input is assigned but output display shows the incorrect value

I have been trying to figure out why my code isn't working properly. I know my code below is a mess (I am a rather poor C programmer thus far). Its a work in progress. Specifically
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
I find that when i run my program I might select a keyboard input of 1, meaning I am looking at my second record in my file entries.txt. The printout of vIndex however is a number much much larger, much likely the last information stored there. Running in debug however, i find that vIndex change to 1 and but prints the strange number. My entire code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec
{
int i;
float PI;
char A;
} Record;
typedef struct
{
char fname[20];
char lname[50];
char phone[15];
} Contact;
Record * arrayAlloc(int size);
char * stringAlloc(int size);
Contact * contactAlloc();
void structAlloc();
int main(void)
{
int *ptrInt;
Record * ptrRec;
int i = 0;
char * myName;
Contact * contacts;
ptrInt = (int *)malloc(sizeof(int));
int vIndex=0;
int displayMenu();
Contact * contactAlloc();
// void searchIndex();
void searchFirst();
void searchLast();
void searchPhone();
contacts = contactAlloc();
char choice;
choice = displayMenu();
while (choice !=5)\
{
if (choice == 1)
// searchIndex();
{
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
// fgets(vIndex, 700, stdin);
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. \nPhone Number:\t%c.\n\n ", &vIndex, contacts[vIndex].fname, contacts[vIndex].lname, contacts[vIndex].phone);
}
else if (choice == 2)
searchFirst();
else if (choice == 3)
searchLast();
else if (choice == 4)
searchPhone();
choice = displayMenu();
}
printf("Thank for you using this program.\n");
return 0;
}
int displayMenu()
{
int choice = 0;
while (choice!= 1 && choice != 2 && choice != 3 && choice != 4 && choice!=5)
{
printf("\nWelcome to the phone book application. Please choose from the following options:");
printf("\n\n\t 1) Search the phone book by index. \n\t 2) Search the phone book by first name. \n\t 3) Search the phone book by last name. \n\t 4) Search the phone book by phone number. \n\t 5) Quit.\n\n");
scanf("%d", &choice);
}
return choice;
}
Contact * contactAlloc()
{
FILE * fin;
int count = 0, i = 0;
char aLine[100];
Contact * ptrContact;
fin = fopen("entries.txt", "r");
if (fin != NULL)
{
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
count++;
}
fseek(fin, 0L, SEEK_SET);
count = count / 3;
ptrContact = (Contact *) calloc(count, sizeof(Contact));
count = 0;
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
if (aLine[strlen(aLine) - 1] == '\n')
{
aLine[strlen(aLine) - 1] = '\0';
}
if (i % 3 == 0)
{
strcpy(ptrContact[count].lname, aLine);
}
else if (i % 3 == 1)
{
strcpy(ptrContact[count].fname, aLine);
}
else if (i % 3 == 2)
{
strcpy(ptrContact[count].phone, aLine);
//printf("Line %d at count %d: %s\n", i, count, aLine);
count++;
}
i++;
}
//count=count*3;
printf("%d contacts loaded.\n\n", count);
fclose(fin);
}
return ptrContact;
}
/*
void searchIndex()
{
int vIndex=0;
printf("Please enter the index of the contact you wish to view. This should be a positive integer");
scanf("%d", &vIndex);
fgetc(stdin);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. Phone Number:\t%c.\n\n ", &vIndex, &Contact[vIndex].fname, &Contact[vIndex].lname, &Contact[vIndex].phone);
}
*/
void searchFirst()
{
}
void searchLast()
{
}
void searchPhone()
{
}
You are printing the address of vIndex instead of the value:
printf("The value of vIndex is %d", &vIndex);
Change this line to the following:
printf("The value of vIndex is %d", vIndex);

Resources