【发布时间】:2015-12-02 05:35:34
【问题描述】:
所以我有一个程序,它接受一个数据字符串和一个数字,最后是它在要打印的优先级中的位置。我需要使用链表,并且我已经弄清楚了如何使用它,但是该程序的执行方式是在数据字符串的末尾,并且优先级是用户应该输入 NONE 并且程序执行。问题是我对 strcmp 的检查迫使用户输入 NONE 两次来执行程序。我认为我没有正确地将 scanf 用于字符串和 int 值,这就是我的问题所在,但我不确定。
这是一个正确的示例输入:
andk81739wewe 7
qweod125632ao 3
lenlc93012wasd 0
093deaeiao12 5
13jadacas291 3
...
NONE
这是程序执行实际必须输入的内容
andk81739wewe 7
qweod125632ao 3
lenlc93012wasd 0
093deaeiao12 5
13jadacas291 3
...
NONE
NONE
关于为什么必须输入第二个 NONE 才能让程序识别没有输入的任何想法?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LARGE 100
struct node
{
char data[LARGE];
int position;
struct node* next;
};
void sortedInsert(struct node** first, struct node* new_node)
{
struct node* current;
if (*first == NULL || (*first)->position <= new_node->position)
{
new_node->next = *first;
*first = new_node;
}
else
{
current = *first;
while (current->next!=NULL &&
current->next->position > new_node->position)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
struct node *newNode(char *new_data,int position)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
strcpy(new_node->data,new_data);
new_node->position=position;
new_node->next = NULL;
return new_node;
}
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%s \n", temp->data);
temp = temp->next;
}
}
int main(void) {
char job[LARGE],blank[1]={' '},*p,*q;
int number=0,x=0;
q=&blank[1];
struct node* first = NULL;
struct node *new_node = newNode(q,0);
printf("Please enter printing jobs\n");
while(x!=1){
if(strcmp(job,"NONE")==0){
x=1;
}
else{
scanf("%s", job);
scanf("%d", &number);
p=&job[0];
sortedInsert(&first, new_node);
new_node = newNode(p,number);
}
}
printf("Print Job in order from 9-0\n");
printList(first);
return 0;
}
【问题讨论】:
-
您需要在第一个
scanf之后和第二个scanf之前检查strcmp。否则它会读取“NONE”,然后尝试读取 int。 intscanf仅在您输入其他内容(第二个 NONE)时返回(并且失败)。您的代码还有其他问题。例如,job在第一次调用strcmp时未初始化。此外,您应该始终检查scanf的返回值,并确保它不会溢出job缓冲区。 -
感谢@kaylum 的提示!那么我是否应该在创建每个变量时始终对其进行初始化,而不是保持原样?
-
@Senglish。您应该在使用它之前初始化变量。否则,您将获得未定义的行为。
-
但是如果我只是在寻找一件事并且我知道我的输入是预定义的,即我已经有我的程序正在测试的内容,那么预先确定这些变量是什么仍然符合我的兴趣保持良好的编程习惯,或者有点像语法 natzi 的东西,不要粗鲁或任何东西,我只是好奇?
标签: c string linked-list scanf strcmp