I am trying to get this code done quickly for class as I have already been writing it for upwards of 10 hours and I just can't get it to work. Essentially what it is, is a domino program where you enter the first number of the domino, the second number, and then a flag (y will be standard- will have to switch to n when dice is removed). Currently I am receiving errors stating the following:
1. warning: format '%c' expects argument of type 'char ', but argument 2 has type 'void() ()'
2. error: called object 'print' is not a function
3. error: expected expression before 'Domino'
I have sat and researched this issue for hours online and I know I am missing something small. Any assistance would be greatly appreciated
#include <stdio.h>
#include <stdlib.h>
int getIndex();
void addDomino();
void removeDomino();
void print();
void quit();
typedef struct Domino{
int * i;
int * x;
int * y;
}Domino;
int main(int argc, char * argv[])
{
int NumDom, DomNum1, DomNum2, DomIndex, Index, input;
char MainMenu;
//Startup
printf("Enter the max number of dominos:");
scanf("%d",&NumDom);
void * add = malloc(size(Domino)*1);
void * remove = malloc(offset(Domino)*1);
void * print = malloc(sizeof(Domino)*10);
//int domino[NumDom][3];
//int dom[0][3] = {Index, DomNum1, DomNum2};
//Main Menu
// printf("Enter (p) to print (a) to add (r) to remove and (q) to quit\n");
// printf(":");
// scanf("%s",&MainMenu);
printf("Enter (p) to print (a) to add (r) to remove and (q) to quit\n");
scanf("%c%c%c%c \n", addDomino, removeDomino, print, quit);
switch(input)
{
case 'a':
addDomino();
break;
case 'r':
removeDomino();
break;
case 'p':
print();
break;
case 'q':
quit();
break;
printf(":\n");
}
}
//Add
void addDomino(DomNum1, DomNum2)
{
printf("Enter number 1\n");
printf(":");
scanf("%d", &DomNum1);
printf("Enter number 2\n");
printf(":");
scanf("%d", &DomNum2);
}
//Print
void printDomino(DomNum1, DomNum2)
{
printf("Printing Dominos\n");
printf("Domino # (%d,%d)\n",DomNum1,DomNum2);
}
//Remove
void removeDomino(DomIndex)
{
printf("Enter the index:%d", DomIndex);
scanf("%d", &DomIndex);
}
//Quit
void quit()
{
printf("All done\n");
}
HERE IS THE ORIGINAL CODE THAT WORKS MINUS ALL MY FUNCTION ISSUES
#include <stdio.h>
#include <stdlib.h>
typedef struct Domino{
int * i;
int * x;
int * y;
}Domino;
int main(int argc, const char * argv[])
{
int NumDom, DomNum1, DomNum2, DomIndex, Index;
char MainMenu;
//Startup
printf("Enter the max number of dominos:");
scanf("%d",&NumDom);
//int domino[NumDom][3];
//int dom[0][3] = {Index, DomNum1, DomNum2};
//Main Menu
printf("Enter (p) to print (a) to add (r) to remove and (q) to quit\n");
printf(":");
scanf("%s",&MainMenu);
//Add
printf("Enter number 1\n");
printf(":");
scanf("%d", &DomNum1);
printf("Enter number 2\n");
printf(":");
scanf("%d", &DomNum2);
//Print
printf("Printing Dominos\n");
printf("Domino # (%d,%d)\n", DomNum1, DomNum2);
//Remove
printf("Enter the index:5");
scanf("%d", &DomIndex);
//Quit
printf("All done\n");
}
As for the first issue - you're passing function pointer to scant function, I don't understand what you're trying to achieve.
Just give it input variable and that's all.
Your problem is that you're telling scanf to scan for a character, but you're not giving it a character to put the value into. For example, this:
printf("Enter (p) to print (a) to add (r) to remove and (q) to quit\n");
scanf("%c%c%c%c \n", addDomino, removeDomino, print, quit);
Makes no sense. You're asking the user to pick a command but asking for 4 characters to be entered. You just need something like this:
char command;
printf("Enter (p) to print (a) to add (r) to remove and (q) to quit\n");
scanf("%c", &command);
You've also not typed the parameters to your functions. For example this:
void addDomino(DomNum1, DomNum2)
looks like it ought to be this:
void addDomino(int DomNum1, int DomNum2)
and at the top, where you had this:
void addDomino()
it should look like this:
void addDomino(int, int)
This will allow you to call addDomino() from inside main().
Related
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.
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.
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.
I am having problems with the menu function of my program. The last 2 parts of the printf for the menu are continuing onto the next function.
Code for menu function -
#include <stdio.h>
#include <string.h>
void enter(char names[16][20]);
void menu();
int main()
{
char names[16][20];
int i;
printf("Please enter the names of the players:\n");
/*Making the user enter 16 times*/
for (i = 0; i < 16; i++)
{
scanf("%9s", &names[i]);
fflush(stdin);
}
/*Clearing Screen*/
system("cls");
menu();
return names[16][20];
}
void menu(char names[][20])
{
int choice;
printf("Please select one of the following options:\n\n"
"Press 1 to enter game results\n"
"Press 2 to display the current round\n"
"Press 3 to display the players advancing to the next round\n"
"Press 4 to display the previous round\n"
"Press 5 to exit the program\n");
system("cls");
scanf("%d", &choice);
if(choice == 1)
{
enter(names);
system("cls");
}
}
void enter(char names[][20])
{
int result;
int score1;
int score2;
int p, c, j, l, i;
char winner[8][8];
system("cls");
for(i = 0; i < 8; i++)
{
printf("\n\n%s vs %s",names[i],names[i+8]);
score1 = 0;
score2 = 0;
for(j = 0; j < 5; j++)
{
printf("\n\nEnter game %d results, press 1 if %s won or"
" 2 if %s won :\n",(j+1), names[i], names[i+8]);
scanf("%d", &result);
if(result == 1)
{
score1++;
}
if(result == 2)
{
score2++;
}
}
}
Somehow the press 4 and 5 options are getting into the next next function
Image -
https://gyazo.com/7e99cfb42a18d04a144d3d139409d6ec
Ok.. I ran your code with some changes and it ran fine, without the two printf lines that you have shown in your image file.
First thing is, the menu() function you have written wrong. It's prototype showing that it takes no arguments while in it's declaration it take an array. You need to pass the names array to menu function as you are going to pass it to the enter function. So, both the functions menu() and enter() will be taking names array as an argument.
I used the code without system("cls") function as my compiler didn't find it.
So, it has worked at my side, I am getting feeling like, system("cls") is causing you the problem that you shown in the image.
I'm new here, so I have no idea if I posted this correctly. I did everything that the instructor told us to do for this program, but this last one has me stumped because we never talked about sorting in class. It says, "Modify the print() function so that it displays the parts sorted in ascending order by part number." I tried looking through the book and on the internet, but I just caused myself to become even more confused. Can anyone help me? Here's my code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NAME_LEN 25
#define MAX_PARTS 100
struct part {
int number;
char name[NAME_LEN + 1];
int on_hand;
float price;
};
int find_part(int number, const struct part inv[], int np);
void insert(struct part inv[], int *np);
void search(const struct part inv[], int np);
void update(struct part inv[], int np);
void print(const struct part inv[], int np);
int read_line(char [], int);
/**************************************************************
* main: Prompts the user to enter an operation code, *
* then calls a function to perform the requested *
* action. Repeats until the user enters the *
* command 'q'. Prints an error message if the user *
* enters an illegal code. *
**************************************************************/
int main(void)
{
char code;
struct part inventory[MAX_PARTS];
int num_parts = 0;
for (;;)
{
printf("Enter operation code: ");
scanf(" %c", &code);
while (getchar() != '\n') /* skips to end of line */
{
;
}
switch (code)
{
case 'i':
insert(inventory, &num_parts);
break;
case 's':
search(inventory, num_parts);
break;
case 'u':
update(inventory, num_parts);
break;
case 'p':
print(inventory, num_parts);
break;
case 'q':
return 0;
default:
printf("Illegal code\n");
break;
}
printf("\n");
}
}
/************************************************************
* find_part: Looks up a part number in the inv array. *
* Returns the array index if the part number *
* is found; otherwise, returns -1. *
************************************************************/
int find_part(int number, const struct part inv[], int np)
{
int i;
for (i = 0; i < np; i++)
{
if (inv[i].number == number)
{
return i;
}
}
return -1;
}
/****************************************************************
* insert: Prompts the user for information about a new *
* part and then inserts the part into the inv *
* array. Prints an error message and returns *
* prematurely if the part already exists or the *
* array is full. *
****************************************************************/
void insert(struct part inv[], int *np)
{
int part_number;
if (*np == MAX_PARTS)
{
printf("Database is full; can't add more parts.\n");
return;
}
printf("Enter part number: ");
scanf("%d", &part_number);
if (find_part(part_number, inv, *np) >= 0)
{
printf("Part already exists.\n");
return;
}
inv[*np].number = part_number;
printf("Enter part name: ");
read_line(inv[*np].name, NAME_LEN);
printf("Enter quantity on hand: ");
scanf("%d", &inv[*np].on_hand);
printf("Enter the price of the item: ");
scanf("%f", &inv[*np].price);
(*np)++;
}
/************************************************************
* search: Prompts the user to enter a part number, then *
* looks up the part in the inv array. If the *
* part exists, prints the name and quantity on *
* hand; if not, prints an error message. *
************************************************************/
void search(const struct part inv[], int np)
{
int i, number;
printf("Enter part number: ");
scanf("%d", &number);
i = find_part(number, inv, np);
if (i >= 0)
{
printf("Part name: %s\n", inv[i].name);
printf("Quantity on hand: %d\n", inv[i].on_hand);
printf("Item Price: %.2f\n", inv[i].price);
}
else
{
printf("Part not found.\n");
}
}
/*************************************************************
* update: Prompts the user to enter a part number. *
* Prints an error message if the part can't be *
* found in the inv array; otherwise, prompts the *
* user to enter change in quantity on hand and *
* updates the array. *
*************************************************************/
void update(struct part inv[], int np)
{
int i, number, change, userChoice, changePartNum;
float changePrice;
char *changeName[] = {""};
printf("Enter part number: ");
scanf("%d", &number);
i = find_part(number, inv, np);
if (i >= 0)
{
printf("Enter your selection to edit this particular part:\n"
"\t\t Type 1 to change the Part Number\n"
"\t\t Type 2 to change the Part Name\n"
"\t\t Type 3 to change the Price\n"
"\t\t Type 4 to change the Quantity on Hand\n"
"\t\t Type 5 to exit without making changes\n\n"
"\t\t Enter your choice here: ");
scanf("%d", &userChoice);
switch ( userChoice )
{
//printf("Would you like to change the Part Number? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 1:
printf("Enter new part number: ");
scanf("%d", &changePartNum);
inv[i].number = changePartNum;
printf("Change part num: %d\n", changePartNum);
printf("inv[i].number: %d\n", inv[i].number);
break;
//printf("Would you like to change the Part Name? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 2:
printf("Enter new name of part: ");
scanf("%s", changeName);
printf("Change part name: %s\n", changeName);
//strcpy (*changeName, inv[i].name[NAME_LEN + 1]);
//printf("&inv[i].name[NAME_LEN + 1]: %d\n", &inv[i].name[NAME_LEN + 1]);
break;
//printf("Would you like to change the price? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 3:
printf("Enter change in item price: ");
scanf("%f", &changePrice);
inv[i].price = changePrice;
break;
//printf("Would you like to change the quantity on hand? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 4:
printf("Enter change in quantity on hand: ");
scanf("%d", &change);
inv[i].on_hand = change;
break;
case 5:
printf("Exiting the editor.");
break;
default:
printf("Your choice is not on the list.");
break;
}
}
else
{
printf("Part not found.\n");
}
}
/************************************************************
* print: Prints a listing of all parts in the inv array, *
* showing the part number, part name, and *
* quantity on hand. Parts are printed in the *
* order in which they were entered into the *
* array. * *
************************************************************/
void print(const struct part inv[], int np)
{
int i;
printf("Part Number Part Name "
"Quantity on Hand "
" Price\n");
for (i = 0; i < np; i++)
{
printf("%7d\t\t %-5s%31d\t%.2f\n", inv[i].number,
inv[i].name, inv[i].on_hand, inv[i].price);
}
}
/*************************************************************
* read_line: Skips leading white-space characters, then *
* reads the remainder of the input line and *
* stores it in str. Truncates the line if its *
* length exceeds n. Returns the number of *
* characters stored. *
*************************************************************/
int read_line(char str[], int n)
{
int ch = 0;
int i = 0;
while (isspace (ch = getchar()))
{
;
}
while (ch != '\n' && ch != EOF)
{
if (i < n)
{
str[i++] = ch;
}
ch = getchar();
}
str[i] = '\0';
return i;
}
If your professor allows you to use a function from the standard libary, check out C library function to do sort, which provides an answer that shows you how to use qsort(). If you're on linux, you can also get documentation on the function (and other standard library functions) by doing man qsort. If you're not on linux, check out any of the various online man pages.
If not, your professor probably expects you to do your own research. Generally the bubble sort algorithm is taught to beginners because of its simplicity. rosettacode provides pseudo-code on what a bubble sort should look like:
repeat
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Note that in your print function, you already have all you need, the array and its length. You demonstrated this by looping through it and printing out all the member variables. Now you just need to write the algorithm for the sort. One thing you need for the algorithm is the comparator function. You stated that you need to sort by part number. That means your comparator function will probably look like this:
int compare(struct part a, struct part b)
{
return (a.number < b.number);
}
For qsort():
qsort(inv, np, sizeof(part), compare);
In your sorting algorithm (that you should write yourself):
if (item.number at index) > (item.number at (index + 1))