I have the void function void isVaraRegistered that should check for existent numbers in the array that are introduced as varanummer in regVaror. If the introduced number already exists it should break from the regVaror function. I am not sure how to do it. How to set isVaraRegistered to true or false or any combination in fact. Please help!
//lager program lab
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define DEPOSIT 10
#define WORDLENGTH 30
#define MAX 10
struct varor{
int varunummer;
char namn[WORDLENGTH];
int lagersaldo;
};
typedef struct varor Vara;
Vara createVara(int varunummer, char namn[], int lagersaldo){
Vara v;
v.varunummer=varunummer;
strcpy(v.namn, namn);
v.lagersaldo=lagersaldo;
return v;
}
void isVaraRegistered(Vara reg[], int varunummer){
for(int n=0; n<MAX; n++){
if(reg[n].varunummer==varunummer) {
printf("\nError! Varunummer finns redan!\n\n");
}
break;
}
}
void regVaror( Vara reg[], int *pNrOfVaror){
char confirm;
char namn[WORDLENGTH],
tmp[WORDLENGTH];
int varunummer, lagersaldo;
printf("\nÄr du säkert att du vill registrera nya varor?\n1: Ja - (fortsätt)\n2: Nej - (gå tillbaka till menyn)\n");
scanf(" %c%*c", &confirm);// %*c för att inte skippa raden dvs skipppa ange varunummer
switch(confirm){
case '1':
do{
printf("Ange varunummer:");
gets(tmp);
varunummer=atoi(tmp);
isVaraRegistered(reg,varunummer);
printf("Ange namn:");
gets(namn);
printf("Ange lagersaldo:");
gets(tmp);
lagersaldo=atoi(tmp);
reg[*pNrOfVaror]=createVara(varunummer,namn,lagersaldo);
(*pNrOfVaror)++;
printf("\nRegristrera mer varor?\n1: Ja - (fortsätt)\n2: Nej - (gå tillbaka till menyn)\n");
scanf(" %c%*c", &confirm);
}while(confirm=='1');
case '2': break;
}
}
int main(){
int run=1;
Vara vRegister[MAX];
int nrOfVaror=0;
while(run){
char choice;
printf("\n\t\tMeny - Lager Program\n\n\
(1) Regristrera nya varor\n\b\b\b\b\
(2) Skriva ut alla varor\n\
(3) Söka efter varor\n\
(4) Ändra lagersaldot för varor\n\
(5) Sortera varor\n\
(6) Avregristrera varor\n\
(7) Avsluta programmet\n");
scanf(" %c%*c", &choice);
if(choice=='1') regVaror(vRegister, &nrOfVaror);
else if(choice=='7') run=0;
}
return 0;
}
A straight return will do it, but I tend to lean towards a more controlled exit in exceptional situations and let the function run through. Obviously there are scenarios where it's fine to have multiple returns but I try to keep it to a guard at the beginning and maybe a couple of special circumstances prior to finishing. But I wouldn't return from inside a loop. Just makes me feel dirty :)
So in your situation I would actually break as you are doing already which will return anyway... Your code is fine. But I'd lean towards this approach:
void isVaraRegistered(Vara reg[], int varunummer){
int found = 0;
for(int n=0; found == 0 && n<MAX; n++){
if(reg[n].varunummer==varunummer) {
printf("\nError! Varunummer finns redan!\n\n");//existing error msg
found++;
}
}
}
Note that this is just a personal coding style thing. Moving over to C# a few years ago thee was a push in our company to standardise and write a certain way and this sort of controlled execution of letting the full function run through was preferred.
--- Edit:
I was responding to the original code, you've updated since I started responding.
Incidentally, should should set int as your return type and return 1 or 0 indicating yes or no given the name of the function and return the found variable I introduced. Then where the function is called respond accordingly....and take out the printf as the function itself has one responsibility which is to answer the question 'isVaraRegistered?'. Any user I/O should be done outside this function.
Related
I'm a C beginner and am working on a program that registers flights using structs. Each flight has a code that must follow a certain structure: FLI-XXXX, X being integers. I'd like to use the integers part of the code later on, so I thought the best way to scan for it was using both fgets and scanf. After validating the code using auxiliary variables, I would later write it to the flights struct. However, I'm stuck at the validating part.
The problem is, whenever I call the function that validates a code (opt1) inside an if statement, it runs twice and only works as intended the second time around. Here's my code:
#include <stdio.h>
#include <string.h>
typedef struct
{
int num;
char code[5];
}fl;
fl flight[9999];
int Valid(char a[], int b)
{
if((strlen(a) != 4) || (b<0 || b>9999)){
return 0;
}
else if(a[0] !='F' || a[1] !='L' || a[2] !='I' || a[3] != '-'){
return 0;
}
return 1;
}
void opt1(fl a[]){
char tempCode[5];
int tempNum;
do
{
puts("Insert code:");
fgets(tempCode, 5, stdin);
scanf("%d", &tempNum);
puts("");
if (Valid(tempCode, tempNum))
{
printf("Flight %s%d registered. \n", tempCode, tempNum);
}
else
{
puts("Flight # invalid.");
}
} while (Valid(tempCode, tempNum)==0);
}
int main() {
int opt;
//calling opt1 works as intended
opt1(flight);
//calling inside if statement runs opt1() twice, only the second time as intended
scanf("%d", &opt);
if(opt==1){
opt1(flight);
}
return 0;
}
And here's an input:
FLI-1234
1
FLI-1234
That returns:
Flight FLI-1234 registered.
Insert code:
Flight # invalid.
Insert code:
Flight FLI-1234 registered.
I'm not sure why this is happening. Can anyone guide me in the right direction, please? Thank you.
Okay, so I am working on a project right now, and the project is to create a game. Here is the concept below:
Please press any key to begin!
Press the ‘h’ key!
You have 2500 milliseconds to respond!
Press the ‘c’ key!
You have 2400 milliseconds to respond!
Press the ‘k’ key!
You have 2300 milliseconds to respond!
Wrong key! :(
You lose!
You made it through 3 rounds!
Here is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
/*----------------------------------------------------------------------------
- Prototypes -
-----------------------------------------------------------------------------*/
char random1 ();
int cmpChar(char rand2, char user1);
/*----------------------------------------------------------------------------
- Implementation -
-----------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
srand(time(NULL)); /* This will ensure a random game each time. */
time_t cdt;
time(&cdt);
ctime(&cdt);
printf("%s\n", ctime(&cdt));
char ans, randChar;
int gameCont = 1;
int score = 0;
printf("This is a Bop-It Game!\n");
printf("\nPress any key to start\n");
getch();
int i = 2600;
while(gameCont == 1){
randChar = random1();
printf("press the '%c' key!\n", randChar);
ans = getch();
gameCont = cmpChar(randChar, ans);
if (gameCont == 1){
score++;
i -= 100;
printf("You have %d milliseconds to respond!\n", i);
}
}
printf("Your score was %d!\n", score);
return 0;
}
char random1 (){
char randInput;
randInput = (rand()%(122-90)+90);
return randInput;
}
int cmpChar(char rand2, char user1){
if (user1 == rand2){
return 1;
}
if (user1 != rand2){
printf("That is incorrect\n");}
else{
return 0;
}
}
If you can see, I implemented a code that kind of mimics the countdown millisecond thing, but it doesnt actually use a timer, it just uses a loop and print statements.
Im on windows OS, and am trying to use #include <sys/time.h> to create a way to implement a timer, and also have it decrease by 100 milliseconds after each iteration.
If you can help with the whole implementation, great, otherwise just a nudge in the right direction would be greatly appreciated.
I want to display structure members based on user input, but I don't know if I've stored the input properly.
When I try display all people, it just outputs random numbers.
These are the structures and function prototypes
#define MAX_NAME_LEN 15
#define MAX_NUM_PERSON 4
#define MAX_JOB_LENGTH 20
typedef struct birth_date
{
int month;
int day;
int year;
} person_birth_t;
typedef struct person
{
char pName[MAX_NAME_LEN];
char job[MAX_JOB_LENGTH];
person_birth_t birth_t;
} person_t[MAX_NUM_PERSON];
void print_menu (void);
void scanPerson(person_t p, int);
void displayPeople(person_t p);
This is the main code for the program, a menu is printed asking user to input a number, if a user enters 1 then it prompts them to add a person. Entering 2 displays all people entered.
int main(void)
{
/* TODO */
print_menu();
return 0;
}
void print_menu (void)
{
int choice;
person_t p;
static int index = 0;
int *indexP = NULL;
indexP = &index;
/*Print the menu*/
scanf("%d", &choice);
switch (choice)
{
case 1:
if (index < MAX_NUM_PERSON){
scanPerson(p, index);
++*indexP;
print_menu();
} else {
printf("Can't add more people - memory full \n");
print_menu();
}
break;
case 2:
displayPeople(p);
break;
case 3:
exit(0);
break;
default:
print_menu();
}
}
/*function called when add person is chosen from menu */
void scanFlight(person_t p, int index){
/*printf to enter name*/
scanf(" %s", p[index].pName);
/*printf to enter job*/
scanf("%s", p[index].job);
}
void displayPeople(person_t p){
for(int i = 0; i < MAX_NUM_PERSON; i++){
printf("%s %d-%d-%d %s \n",p[i].pName
,p[i].birth_t.month
,p[i].birth_t.day
,p[i].birth_t.year
,p[i].job);
}
}
I've tried other ways to take input and add it to a struct array, but I'm just not sure how to do it right.
person_t p;
Here, you use the local variable p (in print_menu function), so each recursion, you just print the parameters of the local variable that is not initialized.
To solve it, you can declare p as the global variable.
OT, in scanFlight function, to avoid overflow, you should change the scanf function to:
/*printf to enter name*/
scanf("%14s", p[index].pName);
/*printf to enter job*/
scanf("%20s", p[index].job);
And, rename scanPerson to scanFlight, because i do not see any implementation of scanPerson function in your code. I think it's typo, no ?
None of the methods were working, so instead of trying to figure it out, I scrapped the static index and indexP.
Instead, I initialized p with malloc:
person_t *p= malloc(MAX_NUM_PERSON * sizeof(person_t));
I changed the scan function to accommodate for the change and made index a pointer instead, and I made the display function pass the index.
When I ran it, the output was correct.
i wanna make a fuction to print all date in struct array after the user press certain key(1 in that case) and stop the loop, and if he press 2 the loop continue until the array get full or the user press 1
#include <stdio.h>
#include <string.h >
struct dat {
int age;
char name[50];
int score;
int trab[2];
};
int main(void)
{
int x = 0;
struct dat people[20];
for(int i = 0; i < 20; i++)
{
gets(people[i].name);
scanf("%d", &people[i]age);
scanf("%d", &people[i].score );
scanf("%d", &people[i].trab[0]);
scanf("%d", &people[i].trab[1]);
scanf("%d", x);
switch(x)
{
case 1:
break;
case 2:
continue;
}
}
imp(people[i]);
return 0;
}
int imp(struct dat people[i])
{
int i;
printf("%s", people[0].name);
printf("%d", &people[0].age);
printf("%d", &people[0].score );
printf("%d", &people[0].trab[0]);
printf("%d", &people[0].trab[1]);
return 0;
}
Your code cannot compile in this state.
Your compiler should tell you why some line do not compile, first try to correct errors.
Once errors are corrected, turn on compiler warning, and handle them.
The line
#include <string.h >
Will raise this error: fatal error: string.h : No such file or directory
Why a space between h and > ?
The function gets should not be used: from man gets
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
So
gets(people[i].name);
should be
fgets(stdin, people[i].name, sizeof people[i].name);
The following line is missing a dot .
scanf("%d", &people[i]age);
Since x is 0, this next line dereference the NULL pointer (which you don't want):
scanf("%d", x);
You should write:
scanf("%d", &x);
Then you call imp function on people[i], but imp is not declared, and i is not defined (it's a variable local to for loop)
imp(people[i]);
The imp definition is not valid:
int imp(struct dat people[i])
Should be something like:
/* function to display ONE person */
int imp(struct dat people)
or
/* function to display ALL peopel */
int imp(struct dat *people, int number_of_people)
I've got this code, but it doesnt work, what's wrong?
I try to make massive of struct with dynamic size(C language)
after the second use of add_sala(); in main function Windows close programm.
Please help to solve this problem! Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
char trash[50];
int dyn_sala_id=1;
typedef struct
{
int id;
char number[6];
int persons;
char tech_inf[256];
} sala;
sala *sala_;
int add_sala()
{
int persons;
char number[6], tech_inf[256];
sala_ = (sala*)realloc(sala_,dyn_sala_id * sizeof(sala));
printf("Wpisz numer sali(max. 5 znakow): ");
fgets(number,6,stdin);
if(strlen(number)>5)
{
printf("Numer musi byc nie wiecej, niz 5 znakow!\n");
fflush(stdin);
add_sala();
return 0;
}
printf("Wpisz ilosc osob, ktora wmiesci sie w sale(max. 1000 osob): ");
scanf("%d", &persons);
if(persons==0 || persons>1000)
{
printf("Nie wolno wprowadzic litery oraz max. ilosc osob to 1000\n");
fflush(stdin);
add_sala();
return 0;
}
printf("Wpisz info o wyposazeniu sali(max. 255 znakow): ");
fgets(trash,50,stdin);
fgets(tech_inf,256,stdin);
if(strlen(tech_inf)>255)
{
printf("Info musi byc nie wiecej, niz 255 znakow!\n");
fflush(stdin);
add_sala();
return 0;
}
sala_[dyn_sala_id].id = dyn_sala_id;
strncpy(sala_[dyn_sala_id].number, number, 6);
sala_[dyn_sala_id].persons = persons;
strncpy(sala_[dyn_sala_id].tech_inf, tech_inf, 256);
printf("\nSala zostala dodana!\n\n");
printf("%d, %d, %s, %s",dyn_sala_id, persons, number, tech_inf);
dyn_sala_id+=1;
return 0;
}
int main()
{
add_sala();
printf("%s",sala_[1].number);
add_sala();
printf("'%s'",sala_[1].number);
printf("'%s'",sala_[2].number);
return 0;
}
Arrays in C are indexed from 0, so in main() the array indexing is off by 1.
add_sala();
printf("%s",sala_[1].number);
add_sala();
printf("'%s'",sala_[1].number);
printf("'%s'",sala_[2].number);
Also in the function add_sala() it is clear that the first time it is called you have the global
int dyn_sala_id=1;
which you use to allocate memory for one record with
sala_ = (sala*)realloc(sala_,dyn_sala_id * sizeof(sala));
but a bit further down, the indexing is again off by 1, where there is plainly only one array element
sala_[dyn_sala_id].id = dyn_sala_id;
Then, in that same function (although I can't read the error messages) it seems strange that after an apparent bad input, you recurse the function. Also, you have undefined behaviour with
fflush(stdin);
and I have not looked further, because the code will not work.