为什么scanf不能在使用C编程的函数中工作



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

#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Function Type 2n");
x = motivQuote();
printf("Returned value is %dnn", x);
printf("Expected grades this semester:n");
printf("Subject1: ");
y = grade();
printf("nReturned value is %cn", y);
}
int motivQuote()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n == 1)
printf("n~ Robert Collier ~nt"Success is the sum of small efforts, repeated day in and day out."n");
if (n == 2)
printf("n~ David Bly ~nt"Striving for success without hard workntis 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 Functionsn");
x= motivQuote();
printf("Returned value is %dnn", x);
printf("Expected grades this semester:n");
printf("Subject1: ");
y= grade();
printf("nSubject2: ");
z= grade();
printf("Returned values are %c and %cn", y, z);
}

int motivQuote ()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n==1)
printf("n~ Robert Collier ~nt"Success is the sum of small efforts, repeated day in and day out."n");
if (n==2)
printf("n~ David Bly ~nt"Striving for success without hard workntis 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;
}

有人能告诉我是什么原因吗?

使用scanf(" %c",&grade,1);%c前面有空格。这将解决问题。

最新更新