I have made a queue of nodes to store the data.
And the data should be implemented through file I/O.
In .txt file:
"Name1"
"Birthday1 (month date)"
"Genre1"
"Name2"
"Birthday2 (month date)"
"Genre2"
(above form is repeated)
Whenever I try to run through the code, it shows some strange characters for Name, Genre, and Birthday.
Also, same lines are repeated for 14 times.
I guess the problem has to do with data_in function.
What is the problem, and how can I fix it?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
typedef struct node {
char *name, *genre;
int month, date;
struct Node *next;
}Node;
typedef struct Queue {
Node *front;
Node *rear;
int count;
}Queue;
void queue_init(Queue *queue) {
//Initializing needed in order to use the queue
queue->front = queue->rear = NULL;
queue->count = 0;
}
int isEmpty(Queue *queue) {
//Check whehter the queue is empty or not
return (queue->count == 0);
}
void display_node(Node *node) {
printf("\nName: %s", node->name);
printf("\nFavorite Genre: %s", node->genre);
printf("\nBirthday: %d / %d", node->month, node->date);
printf("\n");
}
void data_in(Queue *queue) {
Node *now = (Node *)malloc(sizeof(Node));
FILE *f;
f = fopen("C:\\Users\\brain\\Desktop\\School\\2-2 GWU\\Data Structures and Algorithm\\LAB\\Lab Assignment\\Lab Assignment 3.txt", "r");
for(int i = 0; i < 14; i++) {
char n[100], g[100];
fscanf(f, "%s", &n);
fscanf(f, "%d %d", &now->month, &now->date);
fscanf(f, "%s", &g);
fgets(f);
now->name = (char *)malloc(sizeof(char)*strlen(n));
now->genre = (char *)malloc(sizeof(char)*strlen(g));
now->name = n;
now->genre = g;
if (isEmpty(queue))
queue->front = now;
else
queue->rear->next = now;
queue->rear = now;
queue->count++;
}
fclose(f);
}
void search(Queue *queue) {
Node *now = queue->front;
char c[100], check[100];
int ch, cnt = 0;
printf("Which section do you want to search? (Genre or Month): ");
scanf("%s", &c);
if (strcmp(c, "Genre") == 0) {
printf("Type the genre: ");
scanf("%s", &check);
for (int i = 0; i < queue->count; i++) {
if (now != NULL) {
if (strcmp(now->genre, check)) {
display_node(now);
now = now->next;
cnt = 1;
}
}
}
if (cnt == 0) printf("\n.....No results found...");
}
else if (strcmp(c, "Month") == 0) {
printf("Type month as an integer: ");
scanf("%d", &ch);
for (int j = 0; j < queue->count; j++) {
if (now != NULL) {
if (now->month == ch) {
display_node(now);
now = now->next;
cnt = 1;
}
}
}
if (cnt == 0) printf("\n.....No results found...");
}
}
int main(void) {
int check = 1;
Queue DSA;
queue_init(&DSA);
data_in(&DSA);
while (check == 1) {
search(&DSA);
printf("\nDo you want to continue searching? (1 or 0): ");
scanf("%d", &check);
printf("\n============================================================\n");
}
system("pause");
return 0;
}```
These two lines are definitely NOT what you want:
fscanf(f, "%s", &n);
fscanf(f, "%s", &g);
they should read:
fscanf(f, "%s", n);
fscanf(f, "%s", g);
(notice the removed &).
Also, the next line:
fscanf(f, "%d %d", &now->month, &now->date);
should have a space as the first character of the format string:
fscanf(f, " %d %d", &now->month, &now->date);
Related
I'm having a trouble with my school project. I was asked to use a linked list, I'm almost finish but then I got stuck in how do I sort my data by looking at the date
I want to display these data by sorting the date
I have searched everywhere and I still can't find how to sort a linked list multiple parameters
say these are the parameters:
struct Data {
int kode;
char variety[20];
int weight;
int date;
struct Data *next;
} *headIn, *tempIn;
with a main function like this:
int menu;
int pointIn = 0;
int amount = 0;
void insert(int kode, char *variety, int weight, int date);
void userInput();
void printList(struct Data *tempIn);
int main() {
headIn = NULL;
int menu = 0;
do {
system ("cls");
printf( " \n\nMAIN MENU :\n");
printf( " 1. Input Product\n\n");
printf( " 2. Print List\n\n");
printf( " enter your choice (1 - 2) : ");
scanf("%d", &menu);
if (menu < 1 || menu > 2) {
system("cls");
printf ("your input is not available\n");
getch();
}
switch (menu) {
case 1:
userInput();
break;
case 2:
printList(tempIn);
break;
}
}
while (menu != 3);
system("cls");
printf ("============ Thankyou ============");
return 0;
}
and then I apply this function so that the data is going to be a linked list:
void insert(int kode, char *variety, int weight, int date) {
struct Data *dataIn = (struct Data *)malloc(sizeof(struct Data));
dataIn->kode = kode;
strcpy(dataIn->variety, variety);
dataIn->weight = weight;
dataIn->date = date;
dataIn->next = NULL;
if (headIn == NULL) {
headIn = dataIn;
} else {
dataIn->next = headIn;
headIn = dataIn;
}
}
and then I have this 2 function for asking user's input and the other is for printing
void userInput() {
int code;
int weight;
int date;
amount = 0;
char variety[5][20] = { "Fish", "Crab", "Squid", "Clam", "Lobster" };
system ("cls");
printf("Number of data you want to enter : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for (int i = 0; i < amount; i++) {
printf("\n\nProduct-%d", pointIn + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if (code < 0 || code > 4) {
printf ("this code product is not available\n");
i--;
} else {
printf("\tJenis\t\t : %s\n", variety[code]);
printf("\tINPUT weight\t : "); scanf(" %d", &weight );
printf("\tInput date (YYYYMMDD)\t : ");scanf(" %d", &date);
pointIn++;
insert(code, variety[code], weight, date);
}
}
getch();
}
void printList(struct Data *tempIn) {
system ("cls");
tempIn = headIn;
//sort function here
printf("***** DATA PRODUCT ***** \n" );
printf("| DATE | CODE | NAME | WEIGHT | \n");
while (tempIn != NULL) {
printf(" %d %d %s %d \n", tempIn->date, tempIn->kode, tempIn->variety, tempIn->weight);
tempIn = tempIn->next;
}
getch();
}
please help me I don't understand and I can't find any references, it's just this sorting part I'm stuck in.
In the Insert function, you must find the proper place to insert the node by iterating in the list past the nodes with a lesser date:
void insert(int kode, const char *variety, int weight, int date) {
struct Data *dataIn = (struct Data *)malloc(sizeof(struct Data));
if (dataIn == NULL) {
fprintf(stderr, "cannot allocate memory for Data struct\n");
return;
}
dataIn->kode = kode;
strcpy(dataIn->variety, variety);
dataIn->weight = weight;
dataIn->date = date;
if (headIn == NULL || headIn->date > date) {
// insert node at the head
dataIn->next = headIn;
headIn = dataIn;
} else {
// insert node in the list
struct Data *np = head;
while (np->next && np->next->date >= date) {
np = np->next;
}
dataIn->next = np->next;
np->next = dataIn;
}
}
I have solved my problem for sorting this program
first i add a new struct
struct node{
int kode;
char variety[20];
int weight;
int date;
struct node* left;
struct node* right;
};
struct node* newNode(int data){
struct node* node = (struct node*) malloc(sizeof(struct node));
node->date = data;
node->left = NULL;
node->right = NULL;
return(node);
}
and then i initiate an array
struct Data order[100];
int k=0;
and then make the sorting functions
struct node* insertSort(struct node* node, int data)
{
if (node == NULL)
return(newNode(data));
else
{
if (data <= node->date)
node->left = insertSort(node->left, data);
else
node->right = insertSort(node->right, data);
return node;
}
}
void sort(struct node* node) {
struct node* current = node;
if (node != NULL) {
sort (current->left);
order[k++].date =node->date ;
sort (current->right);
}
}
and then i update my printing process so that it can print the sorted products
void printList(struct Data *tempIn) {
system ("cls");
tempIn = headIn;
int angka =0;
struct node* root = NULL;
while(tempIn!=NULL){
if(root==NULL){
root = insertSort(root, tempIn->date);
}
else {
insertSort(root, tempIn->date);
}
tempIn = tempIn->next;
}
tempIn = headIn;
printf("***** DATA PRODUCT ***** \n" );
printf("| DATE | CODE | NAME | WEIGHT | \n");
k=0;
for (int i=0;i<100;i++){
order[i].date=0;
order[i].kode =0;
order[i].weight=0;
}
sort(root);
tempIn = headIn;
for(int i=0;i<100;i++){
tempIn = headIn;
while (tempIn != NULL) {
if(order[i].date==tempIn->date){
printf(" %d %d %-10s %d \n", tempIn->date, tempIn->kode, tempIn->variety, tempIn->weight);
}
tempIn = tempIn->next;
}
}
getch();
}
In my problem, I need to read lines from a txt file.
Each line contains student_id, name, birthdate, gender, department, and grade(class).
e.g ( 155898933;Nuh Kaplan;26/01/1998;M;ME;2 )
Then I need to store them in a Linked List.
I declared my structure as follows:
struct Node{
int id;
char name[100];
int date; //YYYYMMDD (String date will be converted to integer. I created dateStrInt function for this conversion.)
char gender[2];
char departmentCode[6];
int classGrade;
struct Node *next;
};
Then I read lines and store in an character array with this part of code:
if (fptr != NULL) {
while (fgets (buff, 100, fptr)) {
char* split = strtok(buff, ";");
while( split != NULL ) {
strcpy(arr[i][j], split);
j++;
split = strtok(NULL, ";");
}
i++;
j = 0;
}
}
After I stored lines into character array, I need to store them in a linked list. I tried to do it as follows:
for(int i = 0; i < len; i++) {
p = (struct Node*) malloc(sizeof(struct Node));
j = 0;
p->id = (int)arr[i][j];
strcpy(p->name, arr[i][j+1]);
p->date = dateStrInt(arr[i][j+2]);
strcpy(p->gender,arr[i][j+3]);
strcpy(p->departmentCode, arr[i][j+4]);
p->classGrade = (int)arr[i][j+5];
j = 0;
if(list == NULL){
list = p;
p -> next = NULL;
last = p;
}
else {
last -> next = p;
p -> next = NULL;
last = p;
}
}
However when I run my code, I get garbage values for student id and classGrade.
Can you help me to solve this problem?
My hole code:
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
#include <ctype.h>
struct Node {
int id;
char name[100];
int date; //YYYYMMDD
char gender[2];
char departmentCode[6];
int classGrade;
struct Node *next;
};
int dateStrInt(char str[]) {
int d, m, y;
sscanf(str, "%d/%d/%d", &d, &m, &y);
return (y * 10000 + m * 100 + d);
}
int countLines(char* filename) {
int count = 0;
FILE *fptr;
fptr = fopen(filename, "r");
if(fptr == NULL){
printf("File does not exist.");
exit(1);
}
else {
for(char ch = getc(fptr); ch != EOF; ch = getc(fptr)) {
if(ch == '\n'){
count++;
}
}
}
return count + 1;
}
struct Node* createList(struct Node* list, int len, char filename[]){
struct Node* last;
struct Node* p;
char buff[100];
char arr[len][6][100];
int i = 0, j = 0;
FILE* fptr = fopen(filename,"r");
if (fptr != NULL) {
while (fgets (buff, 100, fptr)) {
char* split = strtok(buff, ";");
while( split != NULL ) {
strcpy(arr[i][j], split);
j++;
split = strtok(NULL, ";");
}
i++;
j = 0;
}
}
int o = 0;
for(int k = 0; k < len; k++){
printf("\nID = %s", arr[k][o]);
printf("\nName = %s", arr[k][o+1]);
printf("\nBirth Date = %s", arr[k][o+2]);
printf("\nGender = %s", arr[k][o+3]);
printf("\nDepartment = %s", arr[k][o+4]);
printf("\nGrade = %s", arr[k][o+5]);
o = 0;
}
for(int i = 0; i < len; i++){
p = (struct Node*) malloc(sizeof(struct Node));
j = 0;
p->id = (int)arr[i][j];
strcpy(p->name, arr[i][j+1]);
p->date = dateStrInt(arr[i][j+2]);
strcpy(p->gender,arr[i][j+3]);
strcpy(p->departmentCode, arr[i][j+4]);
p->classGrade = (int)arr[i][j+5];
j = 0;
if(list == NULL){
list = p;
p -> next = NULL;
last = p;
}
else {
last -> next = p;
p -> next = NULL;
last = p;
}
}
return list;
}
void printList(struct Node *list, int len){
struct Node *p;
p = list;
int cnt = 0;
printf("\nThe list = ");
while(p != NULL) {
if(cnt != len - 1) {
printf("\n{%d, %s, %d, %s, %s, %d} ---->",p->id, p->name, p->date,
p->gender, p->departmentCode, p->classGrade);
cnt++;
}
else
printf("\n{%d, %s, %d, %s, %s, %d} ",p->id, p->name, p->date,
p->gender, p->departmentCode, p->classGrade);
p = p->next;
}
}
int main(void) {
struct Node *head = NULL;
char filename[10];
printf("Enter file name: ");
scanf("%s", filename);
int len = countLines(filename);
struct Node* list = createList(head, len, filename);
printList(list, len);
}
test.txt file :
149875280;Burcu Aksu;04/04/1994;F;CS;3
180201201;Mustafa Kursat Yavuz Tur;12/06/1996;M;CS;3
Output:
Enter file name: test.txt
ID = 149875280
Name = Burcu Aksu
Birth Date = 04/04/1994
Gender = F
Department = CS
Grade = 3
ID = 180201201
Name = Mustafa Kursat Yavuz Tur
Birth Date = 12/06/1996
Gender = M
Department = CS
Grade = 3
The list =
{-1883589280, Burcu Aksu, 19940404, F, CS, -1883588780} ---->
{-1883588680, Mustafa Kursat Yavuz Tur, 19960612, M, CS, -1883588180}
Why are you declaring char array, instead you should be creating array of Node type. Just typecasting the string value to int will not convert the 2 integer fields correctly. Use the conversion function like atoi().
Change this line,
p->id = (int)arr[i][j];
to
p->id = atoi(arr[i][j]);
I am trying to create a print function for my linked list program.
Here is my code so far, the only printing I managed to do is within my readfile function. I have no idea how to use a function to print linked list elements.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct record { // to contain several data types
char process;
char state;
int NUT;
int AT;
int Prio;
struct reord *next;
};
typedef struct record node;
void readfile(node *newlist, node *ncurr, node *next, int quanta, int readincrement, int newincrement, int procnumb, char *fn);
node *crtnode();
main() {
int menu = 0, quanta, readincrement, newincrement, procnumb;
char fn[100];
node *newlist = NULL;
node *ncurr = NULL;
node *next =NULL;
char process, state;
int NUT, AT, Prio;
do {
printf("Selfish RR Algorathim\n");
printf("Enter 1 for existing file\n");
printf("Enter 2 for manual input\n");
printf("Enter 3 for random\n");
printf("Enter 4 for exit\n");
scanf("%d", &menu);
switch (menu) {
case 1:
printf("insert file name");
scanf("%s", &fn);
readfile(newlist, ncurr, next, quanta, readincrement, newincrement, procnumb, fn);
break;
case 2:
printf("boo");
break;
case 3:
printf("haha");
break;
default:
printf("Wrong choice again");
break;
}
} while (menu != 4);
}
void readfile(node *newlist, node *ncurr, node *next, int quanta, int readincrement, int newincrement, int procnumb, char *fn) {
FILE *myFile;
int t;
int j, i;
newlist = NULL;
myFile = fopen(fn, "r");
// reading the values that will be final through out this process
fscanf(myFile, "%d", &quanta);
fscanf(myFile, "%d", &newincrement);
fscanf(myFile, "%d", &readincrement);
fscanf(myFile, "%d", &procnumb);
printf("quanta = %d newinc = %d Readyinc = %d procnumb = %d \n", quanta, newincrement, readincrement, procnumb);
newlist = crtnode(); // creating memory locations for the new list
ncurr = newlist;
for (i = 0; i < procnumb; i++) {
ncurr->process = 'A' + i;
ncurr->state = '-';
fscanf(myFile, "%d", &ncurr->NUT);
fscanf(myFile, "%d", &ncurr->AT);
ncurr->Prio = '\0';
if (i <= procnumb - 1) {
ncurr->next = crtnode();
ncurr = ncurr->next;
}
}
ncurr = newlist;
for (i = 0; i < procnumb; i++) {
printf("\nnode = %p proc = %c state = %c NUT = %d AT = %d priority = %d nextnode = %p\n", ncurr, ncurr->process, ncurr->state, ncurr->NUT, ncurr->AT, ncurr->Prio, ncurr->next);
ncurr = ncurr->next;
}
fclose(myFile);
}
node *crtnode() {
return((node *)malloc(sizeof(node)));
}
When I running this code and call " List() "function it prints only the last added by user . I want to print from beginning to the end.I hope you will help me about my list function.It prints only the last one.
#include<stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
struct seat {
int k_no;
int k_name;
struct seat *next_k, *previous_k;
} *first_k, *temp_k, *last_k;
struct sefer {
char name[20];
int no;
struct sefer *next, *previous;
struct seat *bus;
} *first, *last, *temp;
void list();
void seat_link(int val);
void sefer_search();
int main() {
int val;
printf ("how many names do you want to type ->");
scanf ("%d", &val);
int i;
int j;
for (i = 0; i < val; i++) {
if (first == NULL) {
first = (sefer *)malloc(sizeof(struct sefer));
fflush(stdin);
printf(" %d. name->", i + 1);
scanf("%s", &first->name);
printf(" %d. capacity ->", i + 1);
scanf("%d", &first->no);
first->next = NULL; //2 inci düğüm daha oluşmadığı için null
first->previous = NULL;
last = first; //şimdilik sadece ilk düğüm olduğu için aynı zamanda son oluo
last->bus = NULL;
for (j = 0; j < first->no; j++) {
//KOLTUKLAR OLUŞTURULCAK
if (last->bus == NULL) {
first_k = (seat *)malloc(sizeof(struct seat));
fflush(stdin);
first_k->k_no = j;
first_k->k_name = 1;
first_k->next_k = NULL;
first_k->previous_k = NULL;
last_k = first_k;
last->bus = first_k;
} else {
temp_k = (seat *)malloc(sizeof(struct seat ));
fflush(stdin);
temp_k->k_no = j;
temp_k->k_name = 0;
last_k->next_k = temp_k;
temp_k->previous_k = last_k;
last_k = temp_k;
last_k->last_k = NULL;
}
}
} else if (last == first) {
printf("\n");
last = (sefer *)malloc(sizeof(struct sefer));
fflush(stdin);
printf(" %d. name ->", i + 1);
scanf("%s", &last->name);
printf(" %d. capacitiy ->", i + 1);
scanf("%d", &last->no);
first->next = last;
last>next = NULL;
last->previous = first;
last->bus = NULL;
for (j = 0; j < last->no; j++) {
//KOLTUKLAR OLUŞTURULCAK
if (last->bus == NULL) {
first_k = (seat *)malloc(sizeof(struct seat ));
fflush(stdin);
first_k->k_no = j;
first_k->k_name = 2;
first_k->last_k = NULL;
first_k->previous_k = NULL;
last_k = first_k;
last->bus = first_k;
} else {
temp_k = (seat *)malloc(sizeof(struct seat));
fflush(stdin);
temp_k->k_no = j;
temp_k->k_name = 0;
last_k->next_k = temp_k;
temp_k->previous_k = last_k;
last_k = temp_k;
last_k->last_k = NULL;
}
}
} else { // kayıt eklenmişse diğer düğümler oluşturulcak
printf ("\n");
temp = (sefer *) malloc(sizeof(struct sefer));
fflush(stdin);
printf(" %d. name", i + 1);
scanf("%s", &temp->name);
printf(" %d. capacity->", i + 1);
scanf("%d", &temp->no);
last->next = temp;
temp->previous = last;
last = temp;
last->next = NULL;
last->bus = NULL;
for (j = 0; j < temp->no; j++) {
//KOLTUKLAR OLUŞTURULCAK
if (last->bus == NULL) {
first_k = (seat*)malloc(sizeof(struct seat));
fflush(stdin);
first_k->k_no = j;
first_k->k_name = 3;
first_k->last_k = NULL;
first_k->previous_k = NULL;
last_k = first_k;
last->bus = first_k;
} else {
temp_k = (seat *)malloc(sizeof(struct seat));
fflush(stdin);
temp_k->k_no = j;
temp_k->k_name = 0;
last_k->next_k = temp_k;
temp_k->previous_k = last_k;
last_k = temp_k;
last_k->next_k = NULL;
}
}
}
}
list();
system("PAUSE");
return 0;
}
void sefer_search() { //bağda arama yapar
int searching;
printf("\n\t\t Aranacak Sefer Numarasını Giriniz:");
scanf("%d", &searching);
temp = first;
while (1) {
if (temp->no == searching) {
break;
}
temp = temp->next;
}
}
void seat_link(int val) {
int j;
}
my problem is here actually :
void list() {
temp = first;
while (temp != NULL) {
printf("\t%s --%d \n", temp->name, temp->no);
temp = temp->next;
}
printf ("\n");
last->bus = first_k;
while (last->bus != NULL) {
printf("\t%d --%d \n", last->bus->k_name, last->otobus->k_no);
last->bus = last->bus->next_k;
}
}
Please help me
There are a bunch of problems with your code. Firstly, it won't compile for various reasons. For instance, you sometimes use a struct koltuk without ever defining it. "koltuk" means "seat" in Turkish, so I'm going to assume you meant struct seat in all those cases. Secondly, deg is undefined; I assume you meant val.
There were a few other problems like that which I was able to fix by making plausible guesses. But that leaves the following fundamental problems:
You are using global variables as local variables, for instance temp_k and temp. This makes it well-nigh impossible for a human to analyze your code and understand the control flow.
You have copied code all over the place. You have three separate code blocks to allocate and initialize a sefer depending upon whether it's first in the global linked list, second, or later. Use subroutines!
Your data model seems confused. You have global variables struct *first_k,*temp_k,*last_k; which makes it seem like you have one global linked list of seats for all sefer structs, but the struct seat does not refer back in an obvious way to the sefer that owns it, which implies that each sefer has a separate, private list of seats.
Taking all three problems together, I can't really see where, specifically, you are going wrong. I took a cut at rewriting your code to eliminate these problems. Give it a try to see if it solves your problems:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef struct seat{
int k_no;
int k_name;
struct seat *next_k, *previous_k;
} seat;
typedef struct sefer {
char name[20];
int no;
struct sefer *next,*previous;
struct seat *bus;
} sefer;
void list();
sefer *sefer_search();
void link_sefer(sefer **pp_first, sefer **pp_last, sefer *p_added)
{
p_added->next = p_added->previous = NULL;
if (*pp_first == NULL)
{
*pp_first = *pp_last = p_added;
}
else
{
(*pp_last)->next = p_added;
p_added->previous = *pp_last;
*pp_last = p_added;
}
}
void link_seat(seat **pp_first, seat **pp_last, seat *p_added)
{
p_added->next_k = p_added->previous_k = NULL;
if (*pp_first == NULL)
{
*pp_first = *pp_last = p_added;
}
else
{
(*pp_last)->next_k = p_added;
p_added->previous_k = *pp_last;
*pp_last = p_added;
}
}
sefer *create_and_link_sefer(sefer **pp_first_sefer, sefer **pp_last_sefer, int i)
{
sefer *new_sefer;
seat *p_first_seat = NULL;
seat *p_last_seat = NULL;
int j;
// Allocate and initialize sefer
printf ("\n");
new_sefer = calloc(1, sizeof(struct sefer));
fflush(stdin);
printf (" %d. name->",i+1);
scanf ("%s",&new_sefer->name);
printf (" %d. capacity->",i+1);
scanf ("%d",&new_sefer->no);
new_sefer->bus = NULL;
// Link sefer
link_sefer(pp_first_sefer, pp_last_sefer, new_sefer);
// Allocate seats
for(j=0;j<new_sefer->no;j++){
//KOLTUKLAR OLUŞTURULCAK
seat *p_seat = calloc(1, sizeof(struct seat));
fflush(stdin);
p_seat->k_no=j;
p_seat->k_name = (j != 0 ? 0 : (i+1 > 3 ? 3 : i+1)); // I CAN'T FIGURE OUT WHAT THIS IS SUPPOSED TO BE
link_seat(&p_first_seat, &p_last_seat, p_seat);
}
new_sefer->bus = p_first_seat;
return new_sefer;
}
void sefer_list(sefer *first, sefer *last){
sefer *temp=first;
while (temp !=NULL)
{
seat *seat;
printf("\t%s --%d \n", temp->name,temp->no);
for (seat = temp->bus; seat != NULL; seat = seat->next_k)
{
printf("\t\t%d --%d \n",seat->k_name, seat->k_no);
}
printf ("\n");
temp=temp->next;
}
}
sefer *sefer_search(sefer *first, sefer *last){ //bağda arama yapar
int arama;
sefer *temp;
printf ("\n\t\t Aranacak Sefer Numarasını Giriniz:");
scanf ("%d",&arama);
temp=first;
while (temp != NULL){
if (temp->no==arama){
break;
}
temp=temp->next;
}
return temp;
}
sefer *first = NULL;
sefer *last = NULL;
int main( )
{
int val;
int i;
printf ("how many names do you want to type ->");
scanf ("%d",&val);
for(i=0;i<val;i++){
create_and_link_sefer(&first, &last, i);
}
sefer_list(first, last);
system("PAUSE");
return 0;
}
It seems to work, but since I don't know what you are trying to do, it might not be working as you want.
Judging by the logic, that means that temp really isn't going anywhere. My guess is that when you set those pointers *first, *last, *temp; in the first few lines of main, you don't really point first to NULL, causing it to skip the first if statement. Pointers don't point to NULL by default, they point to whatever was at that memory location beforehand. In this case, garbage. Try adding first=NULL; prior to your first if-statement.
I am coding for a simple linked list , but facing a little problem. The program is like it is accepting name, age and DOB through user, and memory for it is dynamically allocated. After taking data from the user, it is searching a name, asked by user, if the name exists, it should print all the details related to it.
Here is my code-
//function declarations
struct node *initnode(char *, char *, char *);
void add(struct node *);
struct node *printnode(struct node *);
struct node *searchname(struct node *, char *);
struct node {
char name[25];
char age[10];
char dob[10];
struct node *next;
};
struct node *head = (struct node *) NULL;
struct node *initnode(char *name, char *age, char *dob1)
{
struct node *ptr;
ptr = (struct node *) malloc(sizeof(struct node));
if (ptr == NULL)
return (struct node *) NULL;
else {
strcpy(ptr->name, name);
strcpy(ptr->age, age);
strcpy(ptr->dob, dob1);
ptr->next = NULL;
return ptr;
}
}
struct node *printnode(struct node *ptr)
{
printf("Name -> %s\n", ptr->name);
printf("age -> %s \n", ptr->age);
printf("dob ->%s\n", ptr->dob);
return ptr;
}
void add(struct node *newp)
{
struct node *temp = (struct node *) malloc(sizeof(struct node));
if (head == NULL)
head = newp;
else {
for (temp = head; temp->next != NULL; temp = temp->next);
temp->next = newp;
temp = newp;
}
free(temp);
}
struct node *searchname(struct node *ptr, char *name1)
{
if (strcmp(name1, ptr->name) == 0) {
printf("\n name found \n");
printf("\n details are -\n");
printnode(ptr);
return ptr;
} else {
printf("\n name not found in the database \n");
}
}
int main()
{
char name[25];
char name1[25];
char rep;
char age[10];
char dob[10];
int i;
int flag = 1;
struct node *ptr;
do {
fflush(stdin);
while (flag != 0) {
printf("Enter name -- ");
gets(name);
for (i = 0; name[i] != '\0'; i++)
if (isdigit(name[i])) {
printf("Error in user input, name should be in alphabets\n");
flag = 1;
break;
}
else
flag = 0;
}
flag = 1;
while (flag != 0) {
printf("Enter age -- ");
scanf("%s", &age);
fflush(stdin);
for (i = 0; age[i] != '\0'; i++)
if (isalpha(age[i])) {
printf("Error in user input, age should be in numbers\n");
flag = 1;
break;
} else {
flag = 0;
}
}
flag = 1;
while (flag != 0) {
printf("Enter dob in DD/MM/YY format-- ");
scanf("%s", &dob);
fflush(stdin);
for (i = 0; dob[i] != '\0'; i++) {
if (isalpha(dob[i])) {
printf("Error in user input, dob should be in numbers\n");
flag = 1;
break;
} else
flag = 0;
}
}
flag = 1;
ptr = initnode(name, age, dob);
add(ptr);
printf("\n Do you want to continue?<Y/N>:\n ");
scanf("%s", &rep);
//rep = getchar();
}
while (rep == 'Y' || rep == 'y');
printf("\n do u want to search for a name in the database? <Y/N>:\n");
scanf("%s", &rep);
if (rep == 'Y' || rep == 'y') {
printf("Enter name you want to search-- ");
scanf("%s", &name1);
ptr = searchname(head, name1);
} else {
printf("\n goodbye \n");
}
do {
printf("\n do u want to search again? <Y/N>:\n");
scanf("%s", &rep);
if (rep == 'Y' || rep == 'y') {
printf("Enter name you want to search-- ");
scanf("%s", &name1);
ptr = searchname(head, name1);
} else {
printf("\n goodbye \n");
}
}
while (rep == 'Y' || rep == 'y');
return 0;
}
The issue is that it is searching for the first entry only and not others, can anyone help me to sort out this? I am compiling through "gcc".
At a first glance, your search function is only comparing one element, the head of the list.
After comparing one element you must go to the next element. This can either be done recursively or with a while:
Recursive use:
struct node *searchname(struct node *ptr, char *name1)
{
if (ptr==NULL) //Reached end of the list
{
printf("\n name not found in the database \n");
return NULL;
}
if (strcmp(name1, ptr->name) == 0) { //found the element
printf("\n name found \n");
printf("\n details are -\n");
printnode(ptr);
return ptr;
} else { //search next element
return searchname(ptr->next,name1); //this will call your function again for the next element on the list
}
}
While use:
struct node *searchname(struct node *ptr, char *name1)
{
struct node *aux; // usually i use an auxiliary pointer in order to avoid unwanted overwrite at my pointer.
aux = ptr;
while (aux!=NULL)
{
if (strcmp(name1, aux->name) == 0) { //found the element
printf("\n name found \n");
printf("\n details are -\n");
printnode(aux);
return aux;
}
else { //move pointer to next element
aux=aux->next;
}
}
//if it reaches this point, the element was not found
printf("\n name not found in the database \n");
return NULL;
}
Check your add function, it is wrong. Step mentally through it, and see what happens
to your pointer, and to the memory it points to.
What are the malloc and free used for in the add function?