I made this code which asks the user to enter a number of lines and then asks the user, after pressing enter, which line does he want to enter a line. Then prompts the user to type the line he wants to enter. I'm currently have trouble trying to insert the string the user typed to the list. Can someone help me? Here's a copy of what I was able to do:
CODE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct line {
char* line;
struct line *prev, *next;
} LINE;
const int LINE_MAX = 80;
char *addlines(LINE** list, unsigned int line_no);
char *pline = NULL;
LINE *list = NULL; // this will serve as the head of a list.
LINE *endList = NULL; // this points to the last element of a list.
int len=0;
int count=0; //serves as the counter for the number of lines.
char mystring[500]; //serves as the new string that will be inserted.
int main() {
printf("Please enter any number of lines. End with a ^D/^Z:\n");
char line[LINE_MAX];
while(fgets(line, LINE_MAX, stdin)){
len = strlen(line);
count++;
line[len-1] = '\0';
pline = (char *)malloc(sizeof(char) * (len + 1));
strncpy(pline, line, len);
pline[len] = '\0';
LINE *temp;
// test first if your list is non empty
if(list != NULL) {
for(temp = list; temp->next != NULL; temp = temp->next)
;
// at this point, you're at the last element
temp->next = (LINE*)malloc(sizeof(LINE));
temp->next->line = pline;
temp->next->prev = temp;
temp->next->next = NULL;
endList = temp->next;
}
else {// our list is empty
// temp at the last element of the list.
temp = (LINE *)malloc(sizeof(LINE));
temp->line = pline;
temp->prev = temp->next = NULL;
list = temp;
endList = temp;
}
}
LINE* p;
int line_no;
printf("\nEnter the line number where you want to insert a new line:"); //asks the user what line number he wants the string he wants to be printed.
scanf("%d", &line_no);
if(line_no > count) {
printf("\nINVALID.");
}
else {
printf("\nYou want to add a new line on: %d\n\n\n",line_no);
printf("Please enter the line you want to insert:\n\n");
fscanf(stdin, "%s", mystring);
fgets(mystring, 500, stdin);
addlines (list, line_no);
}
return 0;
}
char *addlines (LINE** list, unsigned int line_no) {
LINE *q, *temp;
printf("\nYour new lines\n\n");
for(q = list; q!= NULL; q=q->next) {
temp = (LINE *)malloc(sizeof(LINE));
temp->line = pline;
temp->prev = temp->next = NULL;
list = temp;
q->line;
printf("%s\n", q->line);
}
}
This part here is the problem:
CODE
for(q = list; q!= NULL; q=q->next) {
temp = (LINE *)malloc(sizeof(LINE));
temp->line = pline;
temp->prev = temp->next = NULL;
list = temp;
q->line;
}
I'm actually at the final step of the program which is inserting the line the user entered in the line number the user specified earlier and printing it. As of now, what this code does is to reprint the lines entered by the user during the first part of the program.