使用Enter键结束程序

时间:2011-12-17 08:22:52

标签: c exit

我正在尝试在用户点击Enter键时结束程序。由于某种原因,它似乎不起作用。当我使用“char c不等于输入键”时,它在c中输入一个额外的整数(最后输入的整数)。这段代码有什么问题?

#include <stdio.h>
#include <stdlib.h>
#define framenumber 4

int test1 =0;
int test2=1;
int main(void)
{
    int mainarray[framenumber][2] = {0}, nHP = 3, takein, iPT;
    char c = getchar();
    printf("Enter: ");
    while(1)
    {
        char c = getchar();

        if(c == '\n') {
            printf("here");
        }
        else
        {
            printf("not enter\n");        

            takein = atoi(&c);

            for (iPT = 0; mainarray[iPT][test2] != takein && iPT < framenumber; iPT++);

            if (mainarray[iPT][test2] != takein)
            {
                //search for a victim
                do {
                    nHP = (nHP + 1) % framenumber;
                } while ( !( mainarray[nHP][test1] == 1 ? mainarray[nHP][test1] = 0 : 1 ) );
                //update the page table
                mainarray[nHP][test1] = 1;
                mainarray[nHP][test2] = takein;
            }
            else
            {
                mainarray[iPT][test1] = 1;
            }

            puts("page table:");
            for (iPT = 0; iPT < framenumber; iPT++)
            {
                printf("%s %d, %d.\n", iPT == (nHP + 1) % 4 ? ">": " ", mainarray[iPT][test1], mainarray[iPT][test2]);
            }
            putchar('\n');

            printf("Enter: ");
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:5)

不要创建块变量。 (在循环中)。

  char c='\0';      /* initialize with 0 */
  printf("Enter: ");
  while(c!='\n')   /* loop terminate condition */
   {
        c= getchar(); /* remove declaration  */
        if(c =='\n')
        {
        printf("here");
        }
        else
        {
        getchar();  /*  read (eat) an extra input  */
        printf("not enter\n");
    ....