Taking input using function in C is not working - c

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.

Related

(C) Print an array of structs from a function that calls other function

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.

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.

Taking user input and using a function to check if its valid

I'm trying to create a program in which the user enters three integers, and another function checks to see that their input is valid. If the input is not valid, then the user must input three new numbers.
#include <stdio.h>
int sanitizedInput(int a, int b, int c)
{
if(scanf("%d", &a)==0)
{
printf("Not a number\n");
return 1;
}
else if(scanf("%d", &b)==0)
{
printf("Not a number\n");
return 1;
}
else if(scanf("%d", &c) == 0)
{
printf("Not a number\n");
return 1;
}
else
return 0;
}
int main()
{
int a;
int b;
int c;
int check = 1;
do
{
check = 0;
printf("Enter a number:");
scanf("%d",&a);
printf("Enter a number:");
scanf("%d",&b);
printf("Enter a number:");
scanf("%d",&c);
check = sanitizedInput(a,b,c);
}while(check);
}
However when I run this code, after entering three valid integers nothing shows up in the terminal and the code only terminates after entering 6 integers. (There are other functions and code in the main function, if that code is necessary to find the problem tell me and I will post it.)
Your code and your writing part is not matching.....
You should check the three numbers are valid or not firstly.
int sanitizedInput(int a, int b, int c)
{
if(a==0 || b==0 || c==0)
{
return 1;
}
else
{
printf("They are valid.....\n");
return 0;
}
}
Then if one of them are invalid, you will be able to take another three input for the returning value of 1. Because while(1) is a true condition.
remove
printf("Enter a number:");
scanf("%d",&a);
printf("Enter a number:");
scanf("%d",&b);
printf("Enter a number:");
scanf("%d",&c);
and stay with check = sanitizedInput(a,b,c);, and add printf("something\n") to the
else
return 0; block
and see what happens
In main() you are taking input for three numbers a,b,c and passing these variables as arguments for sanitizedInput().
Here, instead of checking the variables you are again using scanf() which will take new input.
if(scanf("%d", &a)==0)
The above if condition will not check the value of 'a', it will check the return value of scanf() with '0'.
if statement should be like this
if(a==0)
scanf("%d",&a);
this is same for all three variables.
In main function you are passing variables to sanitizedInput(), there you are checking variables and if not valid you are taking input again, so the variable which you changed are local to that function, which will not reflect in main(). So take care about that.
Hope this will help you.
In your while loop,you actually call scanf twice each variable(a,b,c),so you input number for 6 times.When sanitizedInput(a,b,c) finished,it return 0;so check is 0,the loop is over.I think you can do with in your main:
int main
{
int a;
int b;
int c;
int check = 0;
do
{
check = sanitizedInput(a,b,c);
printf("check = %d\n",check);
}while(!check);
return 0;
}

Domino Program Issues

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().

2 questions on typedef struct and averages on grades. Am I doing it correctly In C?

I need help on two questions, Its not homework but its to study for an exam. I need to have these questions because i was allowed 1 full page of notes for the exam. If you could help me these two simple questions for me that would be great. Here are the questions:
"Write a function called getGrades. The function that repeatedly prompts the user for positive integers until the user enters a negative value to stop. The function should return the average of these grades and the highest grade."
"Write a function called Get_Info that takes a pointer to a student structure, (that has three fields: char array called name, an int id, and a double gpa) as its only argument. The function prompts the user for the required information to fill the structure and stores it in the appropriate fields."
What I have so far, Let me know if they are correct and if i need to add anything.
1.
double getGrades() {
double average;
double i;
For(i=1 ; i<i; i++)
{
printf("Enter Grade1:\n");
scanf("%lf", &i);
}
if (i<0)
{
(double) average == (grade1 + grade2 + grade3) / 3;
return average;
}
}
2.
typedef struct {
int id;
double gpa;
char name[SIZE];
} student;
void Get_Info(student list[], int num) {
int i;
for(i=0; i<num; i++) {
printf("\nName:%s", list[i].name);
printf("\nGPA:%lf", list[i].gpa);
printf("\nID: %d\n", list[i].id);
}
}
On #1: The requirement is that the function accept ints. You are scanning for doubles.
The requirement is "The function should return the average of these grades and the highest grade." You only return one double, when two different outputs are called for.
Your for loop is written as "For" (C is case-sensitive), and is based on the test i<i. When will i ever be less than itself??
Here's my version of it.
double getGrades(int* max)
{
int sum = 0;
int input;
int i = 0;
*max = 0;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
while (input > 0) {
if (*max < input) {
*max = input;
}
sum = sum + input;
i++;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
}
return i? ((double)sum / i) : 0;
}
Your #2 is much better than your #1, but still has some errors:
The requirement is that the function takes a pointer to a student struct, NOT an array.
It should then print a series of Prompts, and get a series of answers (just as you did in #1).
This is a sequence of printf/scanf.
And when using scanf, you typically pass the ADDRESS of the variable, using &.
(strings are a exception, however)
Here is my version:
typedef struct {
char name[SIZE];
int id;
double gpa;
} student;
void Get_Info(student* ps) {
printf("Enter Name\n");
scanf("%s", ps->name);
printf("Enter ID:\n");
scanf("%d", &ps->id);
printf("Enter GPA\n");
scanf("%lf", &ps->gpa);
}
Try this. It should seem intuitive enough:
double getGrades() {
double average;
double grade;
double total = 0;
int count = 0;
while (1) {
printf("Enter grade: ");
scanf("%d", &grade);
if (grade < 0) {
if (count == 0) {
average = 0;
break;
}
average = total/count;
break;
}
count++;
total += grade;
}
return average;
}

Resources