How to write an input handling function without global variables? - c

I want to write a function that will filter the input of the user and then give the filtered string back to the function that had called it.
Is this possible without creating an global variable as in my example?
#include <stdio.h>
char input[10]; //global variable is meh!
char* input_function() {
scanf("%s", input);
return input;
}
int main(void) {
printf("%s", input_function());
}

Create a character pointer in the main() function and then pass it as an argument to input_function().
#include <stdio.h>
char* input_function(char* input) {
scanf("%s", input);
return input;
}
int main(void)
{
char input[10]; // Need to allocate space
printf("%s", input_function(input));
}

Is this possible without creating an global variable as in my example?
As the other answer shows, yes, of course it is possible.
However, be careful about applying a blanket meh to global variables, which have their place.
Also be mindful that C allows module-scope, meaning it is accessible within the module, but not externally. These should not be dismissed.
So it is perfectly acceptable to do:
#include <stdio.h>
static char input[10]; //module scope is OK
static char* input_function() {
scanf("%s", input);
return input;
}
int main(void) {
printf("%s", input_function());
}

Related

How do I store the name of a input string for a different C file?

What I am trying to do is ask the name of someone and then storing it so I can use it for different scripts. Here is what I have so far.
main.c
#include <stdio.h>
#include "functions.h"
int main()
{
printf("welcome to the dungeon crawler.\n");
//ask for the name//
printf("please state your name: ");
char name[100];
scanf("%s", name);
printf("hello %s.\n", name);
main2();
return 0;
}
main2.c
#include <stdio.h>
#include "functions.h"
int main2()
{
printf("%s\n", name);
return 0;
}
functions.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
int name;
#endif // FUNCTIONS_H_INCLUDED
When I try to run it, main2 says (null).
This declaration in main
char name[100];
declares a local variable that is not alive outside main.
This declaration in functions.h
int name;
declares a global variable of the type int that is zero initialized.
You have two choices.
Either the function main2 will have a parameter of the type char * or const char *
int main2( const char *name );
(Place the function declaration in the header functions.h)
and will be called like
main2( name );
Or remove the global variable
int name;
in the header functions.h and instead of it move the local declaration
char name[100];
from the module main.c in the header declaring it like
extern char name[100];
In one of the modules in the file scope you place the variable declaration for example like
char name[100];
On any case the declaration of the function main2 must be placed in functions.h.
When I try to run it, main2 says (null).
Because you did not pass any parameter to that function.
You should use some descriptive name rather than main2. There should be only one main, any other function should have descriptive name that describe what it does. For example:
void printit(const char * string)
{
printf("%s\n", string);
}
Then from your main, you need to pass the name to that function:
printit(name);
As a side note, you should initialise your char buffer, and make sure your scanf does not read more characters than it should:
char name[100] = "";
scanf("%99s", name);

How to use structs within multiple functions in C?

I want my program to ask the user to input the name of a car, the color of the car, and the type of car. I want to do this using a struct and only two functions. The first function takes in the info that the user inputs and the second function simply displays the information that was just put in. I have tried coding this but I have no idea how to use structs within two separate functions. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Automobiles {
char name_of_car[50];
char color_of_car[50];
char brand_of_car[50];
} auto;
void UserInput() {
printf("What is the name of the car?\n");
scanf(" %s", auto.name_of_car);
printf("What is the color of the car?\n");
scanf(" %s", auto.color_of_car);
printf("What is the brand of the car?\n");
scanf(" %s", auto.brand_of_car);
}
void DisplayOutput() {
printf("%s", auto.name_of_car);
printf("%s", auto.color_of_car);
printf("%s", auto.brand_of_car);
}
int main() {
UserInput();
DisplayOutput();
return 0;
}
If you want to pass a structure to your functions as parameters, here is a possible example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Automobile {
char name_of_car[50];
char color_of_car[50];
char brand_of_car[50];
};
void UserInput(struct Automobile *auto) {
printf("What is the name of the car?\n");
scanf(" %s", auto->name_of_car);
printf("What is the color of the car?\n");
scanf(" %s", auto->color_of_car);
printf("What is the brand of the car?\n");
scanf(" %s", auto->brand_of_car);
}
void DisplayOutput(struct Automobile *auto) {
printf("%s", auto->name_of_car);
printf("%s", auto->color_of_car);
printf("%s", auto->brand_of_car);
}
int main() {
// Declare an instance of an Automobile structure.
struct Automobile auto;
// Declare and initialize a pointer to an Automobile structure.
struct Automobile *p_auto = &auto;
// Pass the pointer to the functions.
UserInput(p_auto);
DisplayOutput(p_auto);
return 0;
}
In this example, an instance of the Automobile structure is allocated as a local to the main() function. Then we declare a pointer, and initialize it so that it points to that local instance. Then we pass that pointer to the functions.
Your original code declared an instance of the Automobile structure as a global value and accessed it from within your functions. A possible implementation, but not always an appropriate one...
If you want to learn more, read up on "Pass by value" and "Pass by reference" topics at your local C knowledge provider.

Function to save data as struct on C

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct equipamento {
int codDipositivo;
char nomeEquipamento[40];
char newVar[50];
}Equipamento;
insert(int n, int cat, Equipamento eq[])
{
int codigo;
char newVar[40];
printf("\nNew Var: ");
scanf("%s",&newVar);
eq[n].codDipositivo=newVar;
}
main()
{
Equipamento equipamento[MAX_EQ_DSP];
...a bunch of scanfs
scanf("%d",&n);
scanf("%d",&pr);
insert(n, pr, equipamento);
}
This is a sample of what I have.
on main I have a bunch of scanfs which will update the data showing on the screen but now I want to pass that data into a structure and ask for additional information.
I'm trying to use the updated code but for some reason, instead of 39 chars, it breaks down (returns to the main cycle) after the first char
printf("\nNome do Equipamento: ");
gets(nome);
strcpy(eq[n].nomeEquipamento, nome);
Your problem is this line:
eq[n].codDipositivo=newVar;
In C, you cannot assign arrays, you need to copy them element for element. Remember that C has no string data type, a string is just a NUL-terminated array of char. Luckily there is a function in the C library to help us, strcpy.
strcpy(eq[n].codDipositivo, newVar);
To get the declaration of strcpyyou need to add the following include at the top of your code:
#include <string.h>

Programming with functions and structures using C, getting strange output, no errors

I'm learning a bit C and i'm doing an exercise where i use structures and functions to collect employee infos and just print them out.
I'm declaring the functions and the struct in the header since i need them in both of the other files.
//employee.h
int addEmployee(void);
int printEmployee(int i);
struct employeelist
{
char last [20];
char first[20];
int pnumber;
int salary;
};
The "core" file is executing the both functions. The first function asks for the number of employees and gives a value back for the second function where the information is collected and stored. There are no errors and i've checked the code several times.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int numE;
int i;
int addEmployee(void)
{
struct employeelist employee[5];
int numE;
printf("How many employees do you want to add to the list?: ");
scanf("%d", &numE);
printf("Please type in the last name, the first name,\nthe personal number and the salary of your employees.\n");
for (i=0; i < numE; i++)
{
printf("Last name: ");
scanf("%s", employee[i].last);
printf("First name: ");
scanf("%s", employee[i].first);
printf("Personal number: ");
scanf("%d", &employee[i].pnumber);
printf("Salary: ");
scanf("%d", &employee[i].salary);
}
return numE;
}
int printEmployee(int emp)
{
struct employeelist employee[5];
for (i=0; i < emp; i++)
{
printf("Last name: {%s}\nFirst name: {%s}\nPersonal number: {%d}\nSalary: {%d}\n",employee[i].last,employee[i].first, employee[i].pnumber, employee[i].salary);
}
getchar();
getchar();
return emp;
}
The last file contains the main() function to execute the functions above.
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int emp;
int main ()
{
struct employeelist employee[5];
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Now my problem is that everything works only the output is incorrect. I can't even say what it is. Some kind of random mix of signs, letters and numbers. Since i have no idea where my mistake is, i would be glad about any advise to solve this problem. Thank you.
I have added a screenshot of my output. Maybe it helps.
You're trying to use a local variable, which ceases to exist when the function returns.
int addEmployee(void)
{
struct employeelist employee[5];
/* ... */
}
The variable employee only exists inside the addEmployee() function; and it is a different object every time the function is called.
int printEmployee(int emp)
{
struct employeelist employee[5];
/* ... */
}
This employee has no relation to the one in addEmployee.
But don't do the easy thing now (*); do the right thing: declare the array in the main() function and pass it around.
//employee.h
struct employeelist
{
char last [20];
char first[20];
int pnumber;
int salary;
};
/* add up to `maxemp` employees to the array and
** return number of employees added */
int addEmployee(struct employeelist *, int maxemp);
/* print all employees from index 0 to (nemp - 1) */
int printEmployee(struct employeelist *, int nemp);
Declare an array in main(), and pass it around
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main ()
{
int emp;
struct employeelist employee[5];
int emp = addEmployee(employee, 5);
printEmployee(employee, emp);
return 0;
}
(*) Don't declare a global variable for employees
Edited employee.h and added a main() function
You have a brand new variable in your print function that isn't even initialized. So it contains only garbage and that is printed
The heart of the problem is that you're working with three different arrays of employees instead of the one array that you think you've got. Anything declared within a pair of curly braces in C only 'exists' while the program is executing code inside those braces. You've declared three different arrays of employee structs in three different blocks of code.
To point you in the right direction (irrespective of whether this is homework or self-study, this is a learning exercise so just fixing your code probably isn't what you want) you should think about how you can pass the same employee array to each of your functions in turn. (EDIT: pmg beat me to it.)
Declare the array once, in your main() function as you've already done, and modify your two functions printEmployee() and addEmployee() to take that array as a parameter instead of declaring their own local arrays.
Here is a very simple example using ints showing how parameters and return values work. You'll have to do some reading about pointers to extend this to your case.
int main() {
int number = 2;
int newNumber;
newNumber = timesTwo(number);
printf("number: %d newNumber: %d", number, newNumber);
}
int timesTwo(int param) {
return param * 2;
}
Before you start breaking things out into separate files and working with structs and pointers it is a good idea to practice the concepts of functions, parameters and variables by building simple programs in a single file.
You declare the employee array locally to both functions, so they cannot access each other's data.
The main issue, as others have already said, is that you are declaring a struct employeelist employee[5] in each of your functions. This makes those variables local to their functions and thus inaccessable from one function to the other. So, when printEmployee goes to print, the data it is printing is gibberish.
There are a few things needed to fix this:
Make one declaration of your employee list in your main (which you already have) and then pass that into the functions. You'll need to do the passing by means of the array name so that the functions will treat the array properly.
As a result of the above, you'll need to move the struct declaration to be above the function prototypes and then change the prototypes in employee.h to accomodate the passing of the employeelist.
You'll have to check that the user doesn't try to enter more records than your array has space for. Alternatively, you could just declare a pointer in the main and malloc() the needed memory in the addEmployee function.
A few other suggestions to make things a little easier on yourself:
Call your struct employee (or something like that) and your array employeelist (or something similar).
Use typedef on your struct to shorten & simplify your declarations.
Change your printEmployee to be a void function (i.e. void return type).
Take a look.. Well distribued and simple to read, it just needs a little improvement to become bigger and do the work u want.
typedef struct
{
char last [20];
char first[20];
long int pnumber;
int salary;
}employee;
/* the two functions clearly declared */
int addEmployee(employee const wEmployeeList[]);
void printEmployee( employee const wEmployeeList[], int );
int main()
{
int numberE;
employee employeeList[2];
numberE = addEmployee(employeeList);
printEmployee(employeeList, numberE);
return 0;
}
int addEmployee(employee const wEmployeeList[2]){
int i;
for (i=0; i < 2; i++)
{
printf("Last name: ");
scanf("%s", wEmployeeList[i].last);
printf("First name: ");
scanf("%s", wEmployeeList[i].first);
printf("Personal number: ");
scanf("%ld", &wEmployeeList[i].pnumber);
printf("Salary: ");
scanf("%d", &wEmployeeList[i].salary);
}
return 2;
}
void printEmployee(employee const wEmployeeList[2], int numberEmployee){
int i;
for (i=0; i < numberEmployee; i++)
{
printf("\n\nLast name: %s\nFirst name: %s\nPersonal number: {%ld}\nSalary: {%d}\n \n",wEmployeeList[i].last,wEmployeeList[i].first, wEmployeeList[i].pnumber, wEmployeeList[i].salary);
}
}

Programming with functions using C. The functions are not executed

I'm learning C and doing the exercise of the function chapter. So i have written a small programm with 3 files and two small functions. Sincerly it does not work. I have no errors, the functions are simply not executed and i don't know why.
First of all this is my headerfile which only declares my functions.
//employee.h
int addEmployee(void);
int printEmployee(int i);
So the next file is for the definition of the functions.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int numE;
int i;
int addEmployee(void)
{
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
return i;
}
int printEmployee(int i)
{
printf("%d", i);
getchar();
getchar();
return i;
}
And the last file is used to execute the functions.
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
Using
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
you're basically declaring 2 new functions with 0 arguments.
You're not calling your "old" functions.
This should work, as others have pointed out:
int main ()
{
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Because you're calling addEmployee(), storing it's result to emp and then printing emp using printEmployee. Since printEmployee is declared with one parameter, you just put emp in and it will work.
When you call a function you do not put the return type in front of the call. The call is simply the name of the function and any parameters you are calling it with. So your main function should look like this:
int main() {
addEmployee();
printEmployee(1);
return 0;
}
EDIT: So in your employee.c file, you are trying to use addEmployee() to take a number of employees from the command line and store it in the variable i right? And you want printEmployee() to tell you how many employees were entered? Here's how you would do that.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int i;
int addEmployee(void)
{
int numE;
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
}
int printEmployee()
{
printf("%d", i);
getchar();
getchar();
}
Here's what I did.
First, I made numE a variable local to the addEmployee function that uses it. Generally you should keep variable scope as small as possible. That means keep them down to the lowest level they are used. In this case, numE is only needed by addEmployee() so that's its scope.
Second, I removed the parameter from int printEmployee(int i). It was overriding your i variable at the file level. So you were storing the number read into numE in i but then when you entered printEmployee() you were creating a new, empty i that hid it. When you called printEmployee(1) from main, you were passing the value 1 into i in printEmployee(int i). By removing the parameter, you stop hiding employee.c's i.
Finally, I removed the returns. A function doesn't have to return anything in C. And if you are not going to use the return, then it's just an extra line of code to include it.
There's one more change you'll have to make to make this work, in your lab6.c file. Remove the parameter from the call to printEmployee()
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
addEmployee();
printEmployee();
return 0;
}
Should work the way you expect it now.
you want:
int main ()
{
addEmployee();
printEmployee(1);
return 0;
}
Change this:
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
To this:
int main ()
{
addEmployee();
printEmployee();
return 0;
}
You're re-declaring the functions instead of calling them.
You'll also have to change your printEmployee function to not accept an integer argument; it seems like it should just be using the same global variable as addEmployee. This is a bad idea though; global variables are generally to be avoided. addEmployee should probably return the employee ID, which you could store and then pass into printEmployee.

Resources