我在visualstudio中编写了这段代码,用于根据输入的cgpa标记打印语句,但它没有打印输出,我能知道原因是什么吗?
#include <stdio.h>
int main()
{
float cgpa;
char status[50];
printf("Enter your cgpa: ");
scanf_s("%f", &cgpa);
if (cgpa > 3.0)
{
status[50] = "Second Upper Class ";
if (cgpa > 3.75)
status[50] = "First Class Degree";
}
else
{
if (cgpa > 2.0)
status[50] = "Second Lower Class ";
else
status[50] = "Yet to complete ";
}
fputs(status,sizeof(status), stdout);
return 0;
}
我使用strcpy
编辑了代码,用printf
替换了fputs
,并添加了#pragma warning(disable: 4996)
,用于visual studio警告不使用strcpy_s
:
#include <stdio.h>
#pragma warning(disable: 4996)
int main()
{
float cgpa;
char status[50] = { ' ' }, first[50] = { "First Class Degree" }, second[50] = { "Second Upper Class " }, third[50] = { "Second Lower Class " }, forth[50] = { "Yet to complete " };
printf("Enter your cgpa: ");
scanf_s("%f", &cgpa);
if (cgpa > 3.0)
{
strcpy(status, second);
if (cgpa > 3.75)
strcpy(status, first);
}
else
{
if (cgpa > 2.0)
strcpy(status, third);
else
strcpy(status, forth);
}
printf("%s", status);
return 0;
}
做了一个快速检查并添加了一些非常小的修改。
永远不能保证printf((会立即显示输出。控制台不一定以"显示"的形式显示;生的";模式,所以你需要好好踢一下。
您可以使用fflush(stdout)
强制刷新stdout。此外,在printf的字符串后面附加'\n'通常也可以。
#include <stdio.h>
#include <string.h> /* you need this for strcpy */
int main()
{
float cgpa;
char status[50] = { ' ' },
first[50] = { "First Class Degree" },
second[50] = { "Second Upper Class " },
third[50] = { "Second Lower Class " },
forth[50] = { "Yet to complete " };
printf("Enter your cgpa: ");
fflush(stdout); /* Ensure the question is displayed */
scanf("%f", &cgpa); /* I used straight scanf() just for the test */
if (cgpa > 3.0)
{
strcpy(status, second);
if (cgpa > 3.75)
strcpy(status, first);
}
else
{
if (cgpa > 2.0)
strcpy(status, third);
else
strcpy(status, forth);
}
printf("n%sn", status); /* added 'n' for clearer output */
fflush(stdout);
return 0;
}