我使用GNU GCC编译器编写代码块编辑器。我编写了下面的代码(包括相关的库和头文件)
int main() { char a; scanf("%c",&a); switch(a) { case '1': scanf("%c",&a); if(a=='3') { printf("3\n"); }else { printf("4\n"); } break; case '2': printf("HELLO\n"); break; } return 0; }当我运行代码时,终端显示光标以获得该字符。我键入1并按下返回键。所以它要我输入另一个字符。这次我键入3并再次按下返回键。而不是打印3在终端发生了一些不好的事情:运行时错误。 为什么会这样?我犯了哪个错误?我忽略了一些范围规则吗?如果我做了,我忽略了哪个范围规则?
I am coding in Code-Blocks Editor with GNU GCC Compiler.I wrote the following code(including the relevant libraries and Header files)
int main() { char a; scanf("%c",&a); switch(a) { case '1': scanf("%c",&a); if(a=='3') { printf("3\n"); }else { printf("4\n"); } break; case '2': printf("HELLO\n"); break; } return 0; }When I ran the code,the terminal showed the cursor in order to get the character.I typed 1 and pressed return key.So it wanted me to enter another character.This time i typed 3 and pressed the return key again.Instead of printing 3 at the terminal something bad happened:a runtime error. Why did that happen?Which bad mistake did i made?Did i ignore some Scope Rules?if i did,which scope Rule did i ignore?
最满意答案
该方案没有错。 您只需要跳过上一个scanf留下的'\n'字符。 当你按回车键时 ,一个额外的字符'\n'进入输入缓冲区。 这个'\n'被当前scanf留下。 在下次阅读时, scanf将读取这个剩余字符,并且您将会收到意外的程序行为。
要跳过此换行符,您可以在%c之前放置一个空格
scanf(" %c",&a); // ^^ A space before %c can eat up any number of white spaces.另一种方法是在每次scanf后放置这一行
int ch; while((ch = getchar()) != EOF && ch != '\n');Nothing wrong with the program. You only need to skip the '\n' character left behind by the previous scanf. When you press Enter, then an extra character '\n' goes to the input buffer. This '\n' is left behind by the current scanf. On next read scanf will read this leftover character and you will get unexpected behavior of the program.
To skip this newline character you can place a space before %c
scanf(" %c",&a); // ^^ A space before %c can eat up any number of white spaces.Another way is to put this line after each scanf
int ch; while((ch = getchar()) != EOF && ch != '\n');更多推荐
return,代码,bad,电脑培训,计算机培训,IT培训"/> <meta name="description&quo
发布评论