【问题标题】:c function call errorc函数调用错误
【发布时间】:2012-10-10 06:24:30
【问题描述】:

我今天用c语言测试,做了两个小c文件

main.c

#include<conio.h>
void testing();
int main()
{
    testing();
    getch();
    return 0;
}

测试.c

#include <stdio.h>

void testing()
{
    char ch;
    printf("Hello Testing\n");
    do{
        printf("Enter Character : ");
        ch=getchar();
        printf("You Entered : %c\n",ch);
        testing();
        }while(ch!='N');
}

我面临的问题是它从用户那里读取一个字符,然后循环两次,我不知道为什么

output
Hello Testing
Enter Character : k //(i entered k)
You Entered : k

Hello Testing// why this is displayed twice??
Enter Character : You Entered :// i don't press any key and it moves to next iteration

Hello Testing
Enter Character : // here i can enter character again and it happens again twice

我已经在 Visual Studio 2012 上编译了它。

【问题讨论】:

    标签: c function loops


    【解决方案1】:

    打印完字符后,你重新调用testing()。这让你循环测试。去掉这行就OK了。

    你没有故意是recursion。这是计算机编程的一个充满激情的方面,但不是您打算做的。

    还有一件事,当您按下 Enter 以验证您的输入时,请考虑再次读取以消耗输入缓冲区中留下的换行符。

    【讨论】:

      【解决方案2】:

      因为getchar() 在输入缓冲区中留下了换行符。你可以使用另一个 getchar() 来吃掉换行符。

      ch=getchar();
      getchar();
      

      或者使用 scanf 吃掉前导空格:

      scanf(" %c", &ch);
      

      这样之前的所有\n 都会被忽略。

      【讨论】:

        【解决方案3】:

        显示两次是因为你在那里有递归,这个函数应该做什么你有无限递归?

        【讨论】:

          【解决方案4】:

          您的问题可能是由于您在循环中递归调用 testing() 函数。

          【讨论】:

            猜你喜欢
            • 2020-07-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-22
            • 1970-01-01
            • 2013-07-10
            • 2016-01-18
            相关资源
            最近更新 更多