【发布时间】:2020-12-11 10:31:53
【问题描述】:
我创建了一个程序来生成多项选择考试的结果。该程序应该显示错误总数、空白答案和错误回答的问题的数量。对于以下输入:
6
1..223
(这里.表示空白答案)
123124
输出应该是:
Your result:
Mistakes: 3
Blanks: 2
Your mistakes are following:
4 5 6
Your blanks are following:
2 3
但是代码显示了未定义的行为。它似乎经历了无限循环。期待很快解决我的问题。提前致谢。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node* next;
}node;
void printNode(node* head)
{
node* local = head;
int i = 0;
if(local -> data == 0)
{
printf("0");
return;
}
while(local != NULL)
{
if(i == 3)
{
i = 0;
printf("\n");
}
printf("%d\t", local -> data);
local = local -> next;
++i;
}
}
void freeNode(node** head)
{
node* temp = (*head);
while((*head) != NULL)
{
(*head) = (*head) -> next;
free(temp);
temp = (*head);
}
}
int main()
{
int n, i, flagB, flagM, blnk, mstk;
blnk = mstk = flagB = flagM = 0;
printf("Enter the number of questions: ");
scanf("%d", &n);
char ques[n], ans[n];
if(n == 0)
return 0;
node* headM = (node*)malloc(sizeof(node));
node* nodeM;
node* headB = (node*)malloc(sizeof(node));
node* nodeB;
printf("Enter your given answers: ");
fflush(stdin);
for(i = 0; i < n; ++i)
{
scanf("%c", &ques[i]);
}
fflush(stdin);
ques[n] = '\0';
printf("Enter the solution: ");
for(i = 0; i < n; ++i)
{
scanf("%c", &ans[i]);
}
ans[n] = '\0';
for(i = 0; i < n; ++i)
{
if(ques[i] == '.')
{
++blnk;
if(flagB == 0)
{
headB -> data = i + 1;
headB -> next = NULL;
nodeB = headB;
continue;
}
nodeB -> next = (node*)malloc(sizeof(node));
nodeB = nodeB -> next;
nodeB -> data = i + 1;
nodeB-> next = NULL;
flagB = 1;
}
else if(ques[i] != ans[i])
{
++mstk;
if(flagM == 0)
{
headM -> data = i + 1;
headM -> next = NULL;
nodeM = headM;
continue;
}
nodeM -> next = (node*)malloc(sizeof(node));
nodeM = nodeM -> next;
nodeM -> data = i;
nodeM-> next = NULL;
flagM = 1;
}
}
printf("Your result:\n\tMistakes: %d\n\tBlanks: %d\n", mstk, blnk);
printf("Your mistakes are follwing:\n");
printNode(headM);
printf("\nYour blanks are follwing:\n");
printNode(headB);
freeNode(&headM);
freeNode(&headM);
return 0;
}
【问题讨论】:
-
if(i == 3) .. i = 0;-- 这似乎可能会持续很长时间:)如果您只使用三个结构实例 -- 为什么不创建一个包含 3 个结构的数组?另外,为什么看起来您正在尝试nul-terminate 使用ques[n] = '\0';的int数组? -
为什么不直接将所有内容读取为字符串,然后使用
strtol()或使用带有偏移量的sscanf()解析字符串中的整数? -
对于初学者,您需要修复
scanf("%d", &ques[i]);和scanf("%d", &ans[i]);中的转换说明符和指针不匹配,这会在您的代码中调用Undefined Behavior。给我看一下循环问题——你的逻辑是——我们该怎么说——不太清楚...... -
将
"%d"更正为"%c"我没有得到任何无限循环.. 使用6、1..223和123124结果是Mistakes: 4、Blanks: 2"Your mistakes... 5"和"Your blanks... 3"。你在哪里遇到无限循环? -
char ques[n], ans[n];有更多未定义的行为——两者都太短了,无法容纳n字符的字符串。那应该是char ques[n+1], ans[n+1];为'\0'提供空间。 (我会使用,例如char ques[2*n],让您可以使用fgets()读取整个输入字符串,然后使用ques[strcspn (ques, "\r\n")] = 0;(#include <string.h>) 修剪'\n',这将消除您使用scanf()的循环(不好的做法)
标签: c undefined infinite-loop undefined-behavior infinite