用链表读取 C 中的输入
我制作了一个链接列表。它的元素保留上一个和下一个项目的地址。它从输入文件获取命令。它检测命令并使用以下语句作为参数。 (文本:add_to_front john
-> 表示:add_to_front(john)
)
代码:http://pastebin.com/KcAm1y3L
当我尝试从输入文件发出命令时,它一遍又一遍地给出相同的输出。但是,如果我手动在 main()
中写入输入,它就会起作用。
对于前输入文件:(
add_to_front john
add_to_back jane
add_to_back jane
print
不幸的是)输出是:
>add_to_front john
>add_to_back jane
>add_to_back jane
>print
jane
jane
jane
虽然,如果我写
add_to_front(john);
add_to_back(jane);
add_to_back(jane);
print();
而不是这个命令检查:
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");
}
}
在 main()
中它给出了正确的输出。
我知道有很多问题要问,但这件事困扰了我两天。你认为我做错了什么?
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 main()
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有显示上面的相关代码。最有可能的是,您没有将读取的数据复制到列表中,因此您最终会一遍又一遍地存储最后读取的值。
看看粘贴箱里的代码,确实是这个麻烦;您无需将字符串复制到列表中 - 您只需复制指针即可。您将需要添加代码来为字符串分配空间并复制字符串。如果您可以使用,函数
strdup()
可以轻松完成这项工作。如果没有,您可以轻松编写自己的。请注意,这意味着您也必须释放分配的空间。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.