2012-02-23 77 views
3

对不起,可能是愚蠢的问题,但我想练习循环了一下,出来这个想法。基本上它要求你进入或不进入循环,当你在它,它要求你做的事情。问题是,我进入循环后,它打印两次printf字符串之前传递给scanf一个,并等待输入。我无法弄清楚。 欢迎所有帮助!下面的代码:C循环打印两次字符串? (使用scanf(“%c”))

#include <stdio.h> 

int main() 
{ 
    char check = 'a'; 
    char int_check = 'a'; 
    int b = 0; 
    printf("want to go in? [y or n]\n"); 
    scanf("%c",&check); 
    if (check == 'y') { 
     while (1){ 
      printf("Waiting: \n"); 
      scanf("%c",&int_check); 
      if (int_check == 'q'){ 
       printf("You're out, bye!\n"); 
       break; 
      }; 
     }; 
    } else if (check == 'n'){ 
     printf("You're not in, see ya!\n"); 
    }else { 
     printf("Please, type 'y' or 'n'\n"); 
    }; 
    return 0; 
} 
+0

这个......不应该编译。 – 2012-02-23 21:51:41

+0

我不确定它是否是错误错误,但不应在花括号后面包含所有这些分号。 – 2012-02-23 21:52:32

+0

@DanFego这很愚蠢(或者至少我觉得如此),但没关系。它被视为NOP声明IIRC。 – 2012-02-23 21:53:20

回答

4

如果你输入到终端如下:

x 

第一循环将看到一个x

第二循环将看到一个换行符。

解决此问题的最简单方法是使用sscanf和getline。

+0

谢谢Sharth! 我会尽力:) ...对不起,如果我浪费你的时间与愚蠢的问题:) – WhiteEyeTree 2012-02-23 22:11:53

+0

@WhiteEyeTree:不用担心。这不是一个愚蠢的问题。这是几乎每个人在学习C时都要处理的问题。但要记住的一点是,额外的分号是不必要的,可以改变程序的含义。你应该做'if(condition){...}',并跳过最后的分号。这是不需要的,它添加一个空语句在条件之后执行。 – 2012-02-23 23:32:16

2

可以更改程序以立即响应键盘,即不等待用户按下输入。它需要改变输入终端​​的属性,并且通常比面向线路的输入更加混乱和不便携。 This page介绍了如何做到这一点,这里是修改后的代码以这种方式工作:

#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <termios.h> 

struct termios saved_settings; 

void 
reset_term_mode(void) 
{ 
    tcsetattr (STDIN_FILENO, TCSANOW, &saved_settings); 
} 

int main() 
{ 
    tcgetattr(STDIN_FILENO, &saved_settings); 
    atexit(reset_term_mode); 

    struct termios term_settings; 

    tcgetattr(STDIN_FILENO, &term_settings); 
    term_settings.c_lflag &= ~(ICANON|ECHO); 
    term_settings.c_cc[VMIN] = 1; 
    term_settings.c_cc[VTIME] = 0; 
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_settings); 

    char check = 'a'; 
    char int_check = 'a'; 
    int b = 0; 
    printf("want to go in? [y or n]\n"); 
    scanf("%c",&check); 
    if (check == 'y') { 
     while (1){ 
      printf("Waiting: \n"); 
      scanf("%c", &int_check); 
      if (int_check == 'q'){ 
       printf("You're out, bye!\n"); 
       break; 
      }; 
     }; 
    } else if (check == 'n'){ 
     printf("You're not in, see ya!\n"); 
    }else { 
     printf("Please, type 'y' or 'n'\n"); 
    }; 
    return 0; 
}