I've made a Linked List. Its elements keep both previous and next items' address. It gets commands from an input file. It detects the command and uses the following statement as a parameter. (text: add_to_front john
-> means: add_to_front(john)
)
Code: http://pastebin.com/KcAm1y3L
When I try to give the commands from an input file it gives me same output over and over. However, if I write inputs in mai开发者_开发知识库n()
manually, it works.
For ex input file:
add_to_front john
add_to_back jane
add_to_back jane
print
(unfortunately) the output is:
>add_to_front john
>add_to_back jane
>add_to_back jane
>print
jane
jane
jane
Although, if I write
add_to_front(john);
add_to_back(jane);
add_to_back(jane);
print();
Instead of this command check:
while (scanf("%s",command)!=EOF)
{
if (strcmp(command,"add_to_front")==0)
{
gets(parameter);
add_to_front(parameter);
}
else if (strcmp(command,"add_to_back")==0)
{
gets(parameter);
add_to_back(parameter);
}
else if (strcmp(command,"remove_from_back")==0)
remove_from_back(parameter);
...
printf(" HUH?\n");
}
}
In main()
it gives the correct output.
I know it's a lot to ask but this thing is bothering me for 2 days. What do you think I'm doing wrong?
You don't show the relevant code above. Most likely, you do not copy the data that was read into your list, so you end up storing the last value read over, and over, and over again.
Looking at the code in the paste bin, that is indeed the trouble; you do not copy the strings into your list - you just copy the pointer. You will need to add code to allocate space for the string and copy the string. If it is available to you, the function strdup()
does the job neatly. If not, you can easily write your own. Note that this means you will have to free the allocated space too.
精彩评论