How to detect duplicate string using strcmp() - c

#include<stdio.h>
#include<stdio.h>
#include<string.h>
struct stud
{
char nam[20];
int num;
char letter[5];
};
int main()
{
struct stud s[5];
int i, j;
for(i = 0; i < 5; i++){
printf("Enter the name of student #%d: ", i+1);
scanf("%s", s[i].nam);
printf("Enter the number grade of student #%d: ", i+1);
scanf("%d", &s[i].num);
}
for (j = 0; j < i; j++) {
if (strcmp(s[i].nam, s[j].nam) == 0)
printf("Error. Duplicate name detected.");
}
for(i = 0; i < 5; i++){
if(s[i].num >= 90 )
strcpy(s[i].letter, "A");
else if(s[i].num >= 80)
strcpy(s[i].letter, "B");
else if(s[i].num >= 70)
strcpy(s[i].letter, "C");
else if(s[i].num >= 60)
strcpy(s[i].letter, "D");
else
strcpy(s[i].letter, "F");
}
for(i = 0; i < 5; i++)
printf("\n%s has a %s ", s[i].nam, s[i].letter);
return 0;
}
This program has the user enter 5 names and 5 numeric grades, which will then result in the output of their respective letter grades for that student. I'm trying to make it so if the user enters a duplicate name, and message will print saying they can't do that. My attempt in trying to do this is as follows:
for (j = 0; j < i; j++) {
if (strcmp(s[i].nam, s[j].nam) == 0)
printf("Error. Duplicate name detected.");
}
Where I believe that s[j] is the previous string, and compare to see if it equals 0(duplicate) and prints a message. This obviously doesn't work however so I would like to know how to fix this so it can correctly detect duplicate names. Thank you.
Also I have posted this question before but the person that provided an explanation deleted their response before I could provide further questions and ask for clarification. So I am posting this again with an attempt in seeking further aid in what I did wrong in my code.

At the start of the detection loop, i is already 5, so using s[i] is undefined behavior
In your detection loop, i is invariant. you are just comparing a name against the last one [except for the UB, of course].
You need two loops to compare all names against one another.
Also, using 5 everywhere is a "magic number". Better to use a #define (e.g. SMAX)
In the code below, I use cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Here is the corrected code. It is annotated with the bugs and fixes:
#include <stdio.h>
#include <stdio.h>
#include <string.h>
struct stud {
char nam[20];
int num;
char letter[5];
};
#define SMAX 5 // maximum number of students
int
main()
{
struct stud s[SMAX];
int i, j;
for (i = 0; i < SMAX; i++) {
printf("Enter the name of student #%d: ", i + 1);
scanf("%s", s[i].nam);
printf("Enter the number grade of student #%d: ", i + 1);
scanf("%d", &s[i].num);
}
// NOTE/BUG: i is already SMAX, so using s[i] is UB (undefined behavior)
// NOTE/BUG: i never changes
#if 0
for (j = 0; j < i; j++) {
if (strcmp(s[i].nam, s[j].nam) == 0)
printf("Error. Duplicate name detected.");
}
#else
for (i = 0; i < (SMAX - 1); i++) {
for (j = i + 1; j < SMAX; j++) {
if (strcmp(s[i].nam, s[j].nam) == 0)
printf("Error. Duplicate name detected -- %s\n",s[j].nam);
}
}
#endif
for (i = 0; i < SMAX; i++) {
if (s[i].num >= 90)
strcpy(s[i].letter, "A");
else if (s[i].num >= 80)
strcpy(s[i].letter, "B");
else if (s[i].num >= 70)
strcpy(s[i].letter, "C");
else if (s[i].num >= 60)
strcpy(s[i].letter, "D");
else
strcpy(s[i].letter, "F");
}
// NOTE/BUG: newline should go at the end of the printf to prevent a hanging
// last line
#if 0
for (i = 0; i < SMAX; i++)
printf("\n%s has a %s ", s[i].nam, s[i].letter);
#else
for (i = 0; i < SMAX; i++)
printf("%s has a %s\n", s[i].nam, s[i].letter);
#endif
return 0;
}
UPDATE:
Thanks for the tip! On a side note, how would I make it so while the user is entering the duplicate names, the error message appears and the program ends right there.For example: Enter the name of student 1: dan Enter grade: 87 Enter the name of student 2: dan Enter the grade: 78 Error. No duplicate names allowed. And then the program ends there. –
User234567
Easy enough. I put the duplication detection code into functions.
But, I've added a few more enhancements so this may help you with your learning ;-)
I added reprompting the user if they enter a duplicate.
I hate scanf ;-) I reworked the prompting code by putting it into two functions. It will work better if input is a file. This is useful during testing
I changed the conversion from grade number to grade letter to use a table.
Anyway, here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
struct stud {
char nam[20];
int num;
char letter[5];
};
struct letter {
int num;
const char *letter;
};
#define LET(_num,_let) \
{ .num = _num, .letter = _let }
struct letter letters[] = {
LET(90,"A"),
LET(80,"B"),
LET(70,"C"),
LET(60,"D"),
LET(0,"F"),
LET(0,NULL)
};
#define SMAX 5 // maximum number of students
// chkall -- check entire array for duplicates
int
chkall(const struct stud *s,int smax)
{
int i;
int j;
int dup = 0;
for (i = 0; i < (smax - 1); i++) {
for (j = i + 1; j < smax; j++) {
if (strcmp(s[i].nam, s[j].nam) == 0) {
printf("Error. Duplicate name detected -- %s\n",s[j].nam);
dup += 1;
}
}
}
return dup;
}
// chkone -- check a given entry for duplicate (as they are added)
int
chkone(const struct stud *s,int i)
{
int j;
int dup = 0;
for (j = 0; j < i; j++) {
if (strcmp(s[i].nam, s[j].nam) == 0) {
printf("Error. Duplicate name detected -- %s\n",s[j].nam);
dup += 1;
}
}
return dup;
}
// prompt_string -- prompt user for a string
char *
prompt_string(const char *what,int i,char *buf,size_t siz)
{
static int tty = -1;
// decide if our input is tty or file
if (tty < 0) {
struct winsize ws;
tty = ioctl(0,TIOCGWINSZ,&ws);
tty = (tty >= 0);
}
printf("Enter the %s of student #%d: ", what, i + 1);
fflush(stdout);
char *cp = fgets(buf,siz,stdin);
do {
// handle EOF
if (cp == NULL)
break;
buf[strcspn(buf,"\n")] = 0;
// echo the data if input is _not_ a tty
if (! tty)
printf("%s\n",buf);
} while (0);
return cp;
}
// prompt_number -- prompt user for a number
long long
prompt_number(const char *what,int i)
{
char *cp;
char buf[100];
long long val;
while (1) {
cp = prompt_string(what,i,buf,sizeof(buf));
// handle EOF
if (cp == NULL) {
val = -1;
break;
}
// decode the number
val = strtoll(buf,&cp,10);
if (*cp == 0)
break;
printf("invalid number syntax -- '%s'\n",cp);
}
return val;
}
int
main(void)
{
struct stud s[SMAX];
int i;
for (i = 0; i < SMAX; i++) {
while (1) {
prompt_string("name",i,s[i].nam,sizeof(s[i].nam));
if (! chkone(s,i))
break;
}
s[i].num = prompt_number("number grade",i);
}
// recheck all entries
// this will _never_ report a duplicate because of the chkone above
chkall(s,SMAX);
for (i = 0; i < SMAX; i++) {
for (struct letter *let = letters; let->letter != NULL; ++let) {
if (s[i].num >= let->num) {
strcpy(s[i].letter,let->letter);
break;
}
}
}
for (i = 0; i < SMAX; i++)
printf("%s has a %s\n", s[i].nam, s[i].letter);
return 0;
}

Related

C Problem with counting elements in the list of names

I have made one program, where you enter a few characters (10 max). It makes you a list, count average length of surnames, tell about how much different names. But the problem is, when I enter the last number (10) - it sorts me it incorrectly (like 39399349349, 3443993). Beneath I will present my code. I am newbie in C, so please don't shut on me) I am convinced that sorting function is incorrect, but don't know what exactly(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people {
int num[10];
char surname[20];
char name[10];
} peoples[10], c;
int compare_people_num(const void *a, const void *b);
int main()
{
int i, j, k = 0, l = 0, m = 0, n = 0;
float s = 0;
char str[100];
system("chcp 1251 > nul");
for (i = 0, j = 0; i < 10; i++, j++)
{
printf("Enter number, surname, name %d of your human: ", i + 1);
fgets(str, sizeof str, stdin);
sscanf(str, "%d %s %s", &peoples[j].num, &peoples[j].name, &peoples[j].name);
while (str[n] != '\n')
{
if (str[n] != ' ')
{
peoples[j].num[k] = str[n];
}
else
break;
n++;
k++;
}
n++;
k = 0;
while (str[n] != '\n')
{
if (str[n] != ' ')
{
peoples[j].surname[k] = str[n];
}
else
break;
n++;
k++;
}
n++;
k = 0;
while (str[n] != '\n')
{
if (str[n] != '\0')
{
peoples[j].name[k] = str[n];
}
else
break;
n++;
k++;
}
n = 0;
k = 0;
}
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < 10; j++)
{
if (!strcmp(peoples[i].name, peoples[j].name))
m = 1;
}
if (m == 0)
l++;
m = 0;
s = s + strlen(peoples[i].surname);
}
for (i = 0; i < 9; i++)
for (j = 0; j < 9; j++)
if (strcmp(peoples[j].num, peoples[j+1].num) > 0)
{
qsort(peoples, 10, sizeof(struct people), &compare_people_num);
}
for (i = 0; i < 10; i++)
{
printf("%d ", peoples[i].num);
printf("%s ", peoples[i].name);
printf("%s ", peoples[i].surname);
printf("\n");
}
printf("\nYou have %d different names\n", l);
printf("Avarege lenght of surname is = %f\n", s / 10);
}
int compare_people_num(const void *a, const void *b)
{
const struct people *p1 = a;
const struct people *p2 = b;
return p1->num - p2->num; // Change order to reverse sort
}
I went through your code and removed things that weren't needed. In both your input and sorting, it seemed like you were doing things twice. I tried to document the changes I made and explain why they should be made.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// It's generally a good idea to use #define when you have some global constants
// I made some of the constants larger than what you showed to prevent issues
#define MAX_NAME_LEN 40
#define MAX_SURNAME_LEN 40
#define NUM_PEOPLE 10
#define BUFF_LEN 100
// Separate your struct...
struct person {
int num;
char name[MAX_NAME_LEN];
char surname [MAX_SURNAME_LEN];
};
// ... and array decleration
static struct person people[NUM_PEOPLE];
// I added this function, to make it easier to display a person
void print_person (const struct person * p) {
printf("Person %d %s %s\n", p->num, p->name, p->surname);
}
// This function will print out every person in the people array
void print_people (void) {
for (int i=0; i<NUM_PEOPLE; i++) {
print_person(&people[i]);
}
}
// Compares two people by number
int compare_people_num (const void * a, const void * b) {
struct person * p0 = (struct person *) a;
struct person * p1 = (struct person *) b;
return p0->num - p1->num;
}
// Compares two people by name
int compare_people_name (const void * a, const void * b) {
struct person * p0 = (struct person *) a;
struct person * p1 = (struct person *) b;
return strcmp(p0->name, p1->name);
}
int main (void) {
int i;
char buffer[BUFF_LEN];
for (i=0; i<NUM_PEOPLE; i++) {
printf("Enter number, surname, and name of person %d: ", i+1);
fflush(stdout); // fflush makes sure that our text is shown to the user
fgets(buffer, BUFF_LEN, stdin); // Read user input in to buffer
// It's unclear what you were doing here
// This sscanf line takes a line of text, and splits it into a number and two words
// It then stores that number in people[i].num, and stores the words in name and surname
// However, right after this, you have several while loops that appear to be manually doing the same
// thing all over again. If you want to read all of the input in, just the line below is enough
sscanf(buffer, "%d %s %s", &people[i].num, people[i].name, people[i].surname);
}
// We've read all of the people in now
// Uncomment the next line to check out the output at this state:
// print_people();
// To count names, we first need to sort the people by their name
// We do this using a qsort call
qsort(people, NUM_PEOPLE, sizeof(struct person), compare_people_name);
// Once the names are sorted, we'll calculate how many different names there are
// We start the count at 1, and start checking from the second person (index 1)
// This is because the first person will always be unqiue, and we can't compare to
// person negative 1
int n_names = 1;
for (i=1; i<NUM_PEOPLE; i++) {
char * current = people[i].name;
char * previous = people[i-1].name;
if (!strcmp(current, previous)) {
n_names ++;
}
}
// Now we have to sort the people based on their num field
// Again, in your code, it looked like you were doing this more than nessecary
// We just have to call qsort once, as such
qsort(people, NUM_PEOPLE, sizeof(struct person), compare_people_num);
// We will also do a loop through to calculate the average surname length
float avg_surname_len = 0;
for (i=0; i<NUM_PEOPLE; i++) {
avg_surname_len += (float)strlen(people[i].surname);
}
avg_surname_len /= (float)NUM_PEOPLE;
// We're all done! The people are sorted by number.
print_people();
printf("There are %d unique names\n", n_names);
printf("The average surnames is %f characters\n", avg_surname_len);
}

Incorrect output using strcmp

I'm doing the day 8 of the 30 days of code in HackerRank and I am having a problem with strcmp.
The code asks the user for names of people and their numbers, then asks for other names, if a name wasn't entered before, then it outputs Not found, but if it was then it outputs the name and his number. But for some reason, the output only works in the last loop of the for statement.
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
scanf("%i", &n);
} while (n < 1 || n > 100000);
int i = 0;
phonebook people[n];
for (i = 0; i < n; i++) {
scanf("%s %i", people[i].name, &people[i].number);
}
char othernames[n][100];
for (i = 0; i < n; i++) {
scanf("%s", othernames[i]);
}
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
} else {
printf("Not found\n");
}
}
return 0;
}
You didn't find the othernames from the beginning to end to compare peopleevery time, so you need to replace
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
}
else {
printf("Not found\n");
}
}
to
bool found = false;
for (i = 0; i < n; i++) {
for ( j = 0 ; j < n ; j++ ) {
if (strcmp(othernames[j], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
found = true;
}
}
}
if ( found == false ) printf("Not found\n");
The problem is othernames should just be an array of char, not a matrix. And for each othername entered, you must scan whole phonebook to find it or display Not found. As coded, you only test if the i-th othername typed happens to correspond to the i-th entry in the phone book.
Here is a modified version:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
if (scanf("%i", &n) != 1)
return 1;
} while (n < 1 || n > 100000);
phonebook people[n];
for (int i = 0; i < n; i++) {
if (scanf("%99s %i", people[i].name, &people[i].number) != 2)
return 1;
}
for (int i = 0; i < n; i++) {
char othername[100];
if (scanf("%99s", othername) != 1)
break;
int j;
for (j = 0; j < n; j++) {
if (strcmp(othername, people[j].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
break;
}
}
if (j == n) {
printf("Not found\n");
}
}
return 0;
}
Note that it is probably not a good idea to store phone numbers as int values. Better use a char array so an initial 0 is significant and to store longer numbers.

Limitation in the implementation of Brute Force

I have written a code which is supposed to crack a three digit numeric password. This code seems to work if the password is 888 or less than that. If the password is greater than 888, the code shows the following output:
Unable to crack password..
I'd like to know the reason behind this limitation and the solution to this problem. Thanks in advance.
#include <stdio.h>
#include <string.h>
int main()
{
char pswd[5];
char brute[4];
char crack[4];
printf("Program to crack a 3 digit numeric password\n ");
printf("Enter password: ");
scanf("%s", pswd);
int i, j, k;
int flag = 1;
for(i = 48; i < 57; ++i)
{
for(j = 48; j < 57; ++j)
{
for(k = 48; k < 57; ++k)
{
crack[0] = i;
crack[1] = j;
crack[2] = k;
crack[3] = 0;
if(strcmp(crack, pswd) == 0)
{
flag = 0;
break;
}
}
if(flag == 0) break;
}
if(flag == 0) break;
}
flag == 0 ? printf("Password cracked successfully.\
Your password is %s", crack) : printf("Unable to crack password..");
return 0;
}
The problem is that in your for-loops, the number 57 represents the character '9' but you added a strictly less than meaning you will not take the character '9', a simple fix would be to just add <='9' or <=57, so your code would look like:
#include <stdio.h>
#include <string.h>
int main()
{
char pswd[5];
char brute[4];
char crack[4];
printf("Program to crack a 3 digit numeric password\n ");
printf("Enter password: ");
scanf("%s", pswd);
int i, j, k;
int flag = 1;
for(i = '0'; i <= '9'; ++i)
{
for(j = '0'; j <= '9'; ++j)
{
for(k = '0'; k <= '9'; ++k)
{
crack[0] = i;
crack[1] = j;
crack[2] = k;
crack[3] = 0;
if(strcmp(crack, pswd) == 0)
{
flag = 0;
break;
}
}
if(flag == 0) break;
}
if(flag == 0) break;
}
flag == 0 ? printf("Password cracked successfully.\
Your password is %s", crack) : printf("Unable to crack password..");
return 0;
}
You could also change it to work for more than 3 digit numbers, my approach without arrays:
#include <stdio.h>
int main()
{
int pswd,brute = 0;
printf("Program to crack a positive password\n ");
do
{
printf("Enter password: ");
scanf("%d", &pswd);
} while(pswd<0);
while(brute != pswd)
brute++;
printf("The password is %d",brute);
getchar();
return 0;
}

Find missing lower-case letters that are not in a series of words

As stated in the title I am trying to find all lower-case letters that are not in a series of words. There are no upper-case letters, digits, punctuation, or special symbols.
I need help fixing my code. I am stuck and do not know where to go from here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;
printf("Enter your input : ");
scanf("%s", words);
for(i = 0; i < 26; i++){
letters[i] = 0;
}
while(!feof(stdin)){
for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}
printf("\nMissing letters : %c ", b + 97);
return 0;
}
My output is giving me some random letter that I do not know where it is coming from.
Here is a working first implementation.
As well as the comments that have already been made, you should use functions wherever possible to separate out the functionality of the program into logical steps. Your main function should then just call the appropriate functions in order to solve the problem. Each function should be something that is self contained and testable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_INPUT 20 /* Max input to read from user. */
char *readinput(void);
void find_missing_lower_case(char *, int);
int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);
printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);
find_missing_lower_case(user_input, len_input);
/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}
char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);
int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}
*(result + i) = '\0';
return result;
}
void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */
int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */
/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}
/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}
I figured it out and this is the code I used.
int main(void)
{
int array[26];
char w;
int i=0;
for(i=0; i<26; i++) {
array[i]=0; }
printf("Enter your input: ");
scanf("%c", &w);
while(!feof(stdin)) {
array[w-97] = 1;
scanf("%c", &w); }
printf("Missing letters: ");
for(i=0; i<26; i++) {
if(array[i] == 0) {
printf("%c ", i+97); }
}
printf("\n");
return 0;
}

Creating a program in C that saves and shows data

I'm new with C, and on the university they are making us create a program that can save data introduced by the user, read the data and check if it’s well introduced. After that it must save that data in each free space, you have 10 empty spaces for saving the data. With all the data saved it must show also the data and compare it with all the data introduced. I made the part of reading the data introduced and cheking if its ok. The problem that I have is that I don’t know how I could make the data base and show that data. Here is the code that I have till now.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[30];
int num_sample;
char section;
int cabin;
int day;
int month;
int year;
}Species;
int menu() {
int op = 0;
printf ("\nPrototype Nature Reserve.\n");
printf ("1. Insert a new species.\n");
printf ("2. List the species housed.\n");
printf ("3. Show stadistics.\n");
printf ("4. Exit.\n");
printf ("\nIntroduce an option: ");
scanf ("%d", &op);
return op;
}
void New_species() {
Species e;
int i, j;
char species[100];
char aux[10];
printf("Enter data:\n");
//A fflush is made to not have a problem with the number entered in the menu
fflush(stdin);
gets (species);
//While it is different from - read the text
for (i = 0; species[i] != '-'; i++) {
e.name[i] = species[i];
}
e.name[i] = '\0';
i++;
//We add 1 to the position i because is ending in - and should start reading from the following
for (j = 0; species[i] != '-'; i++,j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.num_sample = My_atoi(aux);
// Check that the sample is a number and not a character
if (e.num_sample <= 0 || e.num_sample >= 100) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the day introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.day = My_atoi(aux);
//Controls the format of the day
if (e.day <= 0 || e.day > 31) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the month introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.month = My_atoi(aux);
//Controls the format of the month
if (e.month <= 0 || e.month > 12) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the year introduced
for (j = 0; species[i] != '-'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.year = My_atoi(aux);
//Controls the format of the year
if (e.year < 1970 || e.year > 2060) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the section introduced
e.section = species[i];
//Controls that the section is in capital letters
if (e.section < 'A' || e.section > 'Z') {
printf ("--> Error in data format.\n");
}
i+= 2;
//As the cabin is at the end it must reach the \0
for (j = 0; species[i] != '\0'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.cabin = My_atoi(aux);
if (e.cabin < 0 || e.cabin > 20) {
printf ("--> Error in data format.\n");
}
printf ("Species stored successfully (%d/10 free).");
//This printf is just to ensure that the data entered was read correctly
printf ("\n%s", species);
}
int My_atoi(char cad[10]) {
int r = 0;
int i;
for (i = 0; cad[i] != '\0'; i++) {
r = r * 10;
r += cad[i] - '0';
}
return r;
}
void list_species() {
}
void stadistics() {
}
void executeOption(int op) {
switch (op) {
case 1:
New_species();
break;
case 2:
list_species();
break;
case 3:
stadistics();
break;
default:
break;
}
}
int main() {
int op = 0;
do {
op = menu();
executeOption(op);
} while (op != 4);
return 0;
}
I’ve seen that you can use files* so it can create a .txt file for storing but I don’t know how to use it and I don't think that it's allowed in this program.
I'll leave a photo of how it should work
Thanks.
ok u need to save data to a file and load from a file.
here a short code of my and read and write:
#include<stdio.h>
#include<stdlib.h>
typedef struct worker
{
int sal;
char name[25];
}W;
void main()
{
FILE *f;
int i,j=4;
W a[3];
while(j!=3)
{
printf("\nEnter\n[1]write\n[2]read\n[3]exit\n");
scanf("%d",&j);
if(j==1)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","w");
for(i=0;i<3;i++)
{
printf("\nEnter worker name: ");
scanf("%s",&a[i].name);
printf("\nEnter worker sal: ");
scanf("%d",&a[i].sal);
fprintf(f,"%s %d",a[i].name,a[i].sal);
}
if(j==2)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","r");
for(i=0;i<3;i++)
{
fscanf(f,"%s %d",a[i].name,&a[i].sal);
printf("\n%s %d",a[i].name,a[i].sal);
}
}
}
fclose(f);}
and I don't think that it's allowed in this program
why wouldn't you be allowed? Yes indeed you can go through two alternatives
To text file
This is the one proposed by dor in his answer where he shows you the way of writing text through fprintf.
To binary file
You can also write to a file using fwrite/fseek like this example I found surfing around you can check it out here -> c-tutorial-binary-file-io
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
and retrieving back the data from the binary may go this way as the tutorial shows
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
If you are looking for a solution in a .txt file I have a proposal,
#include <stdio.h>
int main(){
FILE *in;
FILE *OUT = fopen("read_at.txt", "w");
char name[20];
char capture[80];
int age = 0;
float grade = 0;
puts("introduce your name:");
scanf("%19s", name);
puts("introduce your age:");
scanf("%i", &age);
puts("introduce your Math grade(0-10):");
scanf("%f", &grade);
fprintf(OUT, "Age %i, Grade %f, Name %s\r\n", age, grade, name);
fclose(OUT);
if(!(in = fopen("read_at.txt","r"))){
fprintf(stderr, "The file could not be opened. \n");
return 1;
}
while (fscanf(in, "Age %i, Grade %f, Name %20[^\n]\n", &age, &grade, name)==3){
printf("A %i years old student has achieved a %f mark in last math exam, that student is: %s", age,grade, name);
}
fclose(in);
}
In this code that I have just created you can see how you can just create one file and read and get its data if it has a concrete format. If you are looking for a database you can just put values separated by “;” and new lines (\n). With that if you save it as .csv you would obtain an excel sheet and quite a good database.
If you are interested in this solution, just let me know if you need any additional help.
Regards,

Resources