为什么发生运行时错误?(Why does the Runtime error occur?)

编程入门 行业动态 更新时间:2024-10-28 19:19:56
为什么发生运行时错误?(Why does the Runtime error occur?)

我使用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

本文发布于:2023-08-03 07:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385207.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   发生   Runtime   error   occur

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!