繁体   English   中英

为什么字符串数组在 C 编程中不打印 output

[英]why string array is not printing the output in C programming

我在visual studio中编写了这段代码来打印基于输入cgpa标记的语句,但它没有打印output,我能知道是什么原因吗?

#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编辑了代码,将fputs替换为printf并添加了#pragma warning(disable: 4996)以用于不使用strcpy_s的 Visual Studio 警告:

#include <stdio.h>
#pragma warning(disable: 4996)      
int main()
{
    float cgpa;
    char status[50] = { '\0' }, 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() 会立即显示 output。 控制台不一定以“原始”模式显示,所以你需要好好踢一下。

您可以使用fflush(stdout)强制刷新标准输出。 此外,将 '\n' 附加到 printf 的字符串通常可以解决问题。

#include <stdio.h>
#include <string.h> /* you need this for strcpy */

int main()
{
    float cgpa;
    char status[50] = { '\0' }, 
         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%s\n", status); /* added '\n' for clearer output */

    fflush(stdout);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM