c函数调用错误

标签 c function loops

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

主.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 上编译了它。

最佳答案

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

ch=getchar();
getchar();

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

scanf(" %c", &ch);

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

关于c函数调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977620/

相关文章:

function - 如何在运行时将函数导入到 QTP 测试中?

c# - 是否可以将变量传递到 for 循环中?

javascript - 图片库行网格javascript

c - 如何将8位int8变量放入char变量中?

c - 在 c 中使用带套接字的线程

用于生成 FCGI 服务器的 C API?

javascript - 如何简洁地赋值并立即调用一个函数变量?

c - 需要帮助返回/传递多个数组

java - 我怎么会误解这些 Java 函数的 Big-O?

c - 实验室代码逻辑错误,C程序初学者