我为什么要两次获得印刷声明?

时间:2017-11-14 14:26:04

标签: c algorithm data-structures

我正在尝试构建一种检测ceratin模式的算法, 但是当进入循环时 代码正在执行两次,即print语句打印两次。 它也会导致算法出现问题。

这里它不仅仅是输入,它直接退出循环。

        scanf("%c",&cha);
        printf("hello %d 66 \n",not_invalid);
        printf("hello %c 67 \n",cha);

这是我的代码:

#include<stdio.h>
struct stack
{
    int info[100];
    int top;
};
typedef struct stack stack;

void push(stack *s,int ele)
{
    s->info[++(s->top)]=ele;
}

int pop(stack *s)
{
    return s->info[(s->top)--];
}
int isEmpty(stack s)
{
    return s.top==-1;
}
void display(stack s)
{
    for(int i=0;i<=s.top;i++) printf("%d \n",s.info[i]);
}
int main() 
{
    stack mystack;
    int not_invalid=1;
    mystack.top=-1;
    printf("Enter the input string , if its over enter m to exit \n");
    char cha;
    scanf("%c",&cha);
    int i=0;
    while(cha!='m' && not_invalid)
    {

       printf("%d \n",i++);

        if(cha!='C' && cha!='D') 
        {
          push(&mystack,cha);
          printf("enter the next char : if 43\n");
          scanf("%c",&cha);
        }
        else
        {
            while(!isEmpty(mystack))
            {
                printf("enter the next char : else \n");
                scanf("%c",&cha);
                if(pop(&mystack)!=cha) 
                {
                    not_invalid=0;
                    break;
                }
            }
            if(mystack.top!=-1)
            {
               printf("OUt from if isEmpty 60 \n");
               not_invalid=1;
               break;
            }
            printf("Enter the next char 64 \n");
            scanf("%c",&cha);
            printf("hello %d 66 \n",not_invalid);
            printf("hello %c 67 \n",cha);
            if(cha!='D') 
            {
              not_invalid=0;
              break;
            }else
            {
              printf("hello %d  66\n ",not_invalid);
              printf("Enter the next char 74 \n");
              scanf("%c",&cha);
            }

        }

    }
    if(not_invalid) printf("Invalid expression \n");
    else
    {
      printf("Valid expression");
    }





}

输出:

 Enter the input string , if its over enter m to exit 
 a
 0 
 enter the next char : if 43
 1 
 enter the next char : if 43
 C
 2 
 enter the next char : else 
 enter the next char : else 
 a
 Enter the next char 64 
 hello 1 66 
 hello 
 67 
 Valid expression 

我不确定是什么导致了这个问题,为什么要打印两次并突然结束循环?

0 个答案:

没有答案
相关问题