【问题标题】:Why scanf is not working in functions using C programming? [duplicate]为什么 scanf 在使用 C 编程的函数中不起作用? [复制]
【发布时间】:2021-07-02 01:15:34
【问题描述】:

我使用 2 个函数编写了这个 C 程序,但在第一种情况下,grade() 没有提示输入:

#include <stdio.h>
int motivQuote();
char grade();

void main()
{
    int x;
    char y, z;
    printf("Programmer-defined Function Type 2\n");
    x = motivQuote();
    printf("Returned value is %d\n\n", x);
    printf("Expected grades this semester:\n");
    printf("Subject1: ");
    y = grade();
    printf("\nReturned value is %c\n", y);
}

int motivQuote()
{
    int n = 0;
    printf("Select quote (1 or 2):");
    scanf_s("%d", &n);
    if (n == 1)
        printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
    if (n == 2)
        printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
    return n + 2;
}
char grade()
{
    char grade = 0;
    scanf_s("%c", &grade, 1);
    return grade;
}

在第二种情况下,grade() 仅在第二次调用中提示输入,但第一次不起作用:

 #include <stdio.h>
    int motivQuote();
    char grade();
    
    void main()
    {
        int x;
        char y, z;
        printf("Programmer-defined Functions\n");
        x= motivQuote();
        printf("Returned value is %d\n\n", x);
        printf("Expected grades this semester:\n");
        printf("Subject1: ");
        y= grade();
        printf("\nSubject2: ");
        z= grade();
        printf("Returned values are %c and %c\n", y, z);
    }
    
    int motivQuote ()
    {
        int n = 0;
        printf("Select quote (1 or 2):");
        scanf_s("%d", &n);
        if (n==1)
            printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
        if (n==2)
            printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
        return n+2;
    }
    char grade()
    {
        char grade = 0;
        scanf_s("%c", &grade,1);
        return grade;
    }

谁能告诉我这是什么原因?

【问题讨论】:

    标签: c function input


    【解决方案1】:

    使用scanf(" %c",&amp;grade,1);,在%c 前加一个空格。这样就可以解决问题了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多