【问题标题】:Why my function read() doesn't work if i put some code before calling it?如果我在调用之前输入一些代码,为什么我的函数 read() 不起作用?
【发布时间】:2021-09-16 06:23:35
【问题描述】:

当我调用函数 read() 时没有放置循环或类似的东西,它才能完美运行,但是当我添加一些代码时它不起作用,这里是代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char read();

int main()
{
    int level = -1;
    char c;
    while (level < 1 || level > 3)
    {
        printf("Select a level 1/2/3 : ");
        scanf("%d", &level);
    }
    printf("Put a character : ");
    c = read();
    printf("Your character : %c", c);
    
    return 0;
}
char read()
{
    char letter;
    letter = getchar();
    letter = toupper(letter);
    while (getchar() != '\n');    
    return letter;
}

【问题讨论】:

标签: c char scanf whitespace getchar


【解决方案1】:

函数getchar 还读取空白字符,例如可以在调用后放入输入缓冲区的换行符'\n'

scanf("%d", &level);

在while循环中。

在函数中调用scanf而不是getchar

char read()
{
    char letter = '\0';
    scanf( " %c", &letter );
    letter = toupper(( unsigned char )letter);
    return letter;
}

注意格式字符串中转换说明符 %c 前的空格。它允许跳过输入流中的空格。

或者函数看起来像

char read()
{
    char letter = '\0';

    scanf( " %c", &letter );
    letter = toupper( ( unsigned char )letter );

    int dummy;
    while ( ( dummy = getchar() ) != EOF && dummy != '\n' );

    return letter;
}

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多