忽略返回值:'scanf'(关闭) [英] return value ignored: 'scanf' (closed)

查看:62
本文介绍了忽略返回值:'scanf'(关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C 编写程序,这是我的功能之一:

I'm writing a program with C and this is one of my functions:

void group3()
{
    char select[5];
    printf("\nDetails etc.");
    printf("\nPlease confirm Yes/No if you would like to subscribe:");
    scanf("%s", select);
    if (select == "Yes")
        printf("Good.");
    else
    {
        printf("Alright.");
        main();
    }
}

但是当我尝试编译和调试程序时,出现了一个名为忽略返回值:'scanf'"的警告.出现.我注意到当我对整数运行 scanf 时也会出现警告,但该程序仍然适用于整数.但是,当我尝试 scanf 字符串时,它不起作用.我试过使用 getchar() 但 getchar() 出现相同的警告.我也尝试过使用 scanf_s 但是当我尝试对字符串进行 scanf_s 时出现同样的问题.我还在我的程序中定义了 _CRT_SECURE_NO_WARNINGS.如果有人能向我解释如何消除此警告/让 scanf 或 getchar 处理字符串,我将不胜感激.

But when I try to compile and debug the program, a warning called "return value ignored: 'scanf'" appears. I noticed that the warning appears when I'm running scanf for integers too but the program still works for integers. However, when I try to scanf for strings, it doesn't work. I've tried using getchar() but the same warning occurs for getchar(). I've also tried using scanf_s but the same problem appears when I try to scanf_s for strings. I've also defined _CRT_SECURE_NO_WARNINGS in my program. Would really appreciate it if someone could explain to me how I can eliminate this warning from occurring/get the scanf or getchar to work with strings.

感谢一些有帮助的用户,我发现问题不是因为没有读取字符串,而是因为我无法以这种方式使用 if 语句比较字符串.答案在评论部分,我无法选择它作为正确答案,但此问题已关闭.谢谢:)

推荐答案

问题是 scanf() 的返回值被忽略了,所以不要忽略它来消除警告.

The problem is that the return value of scanf() is ignored, so don't ignore that to eliminate the warning.

scanf() 成功时返回读取数据的数量,错误时返回负数,因此检查是否成功读取所需的东西很有用.

scanf() returns the number of data read on success and negative number on error, so it is useful to check if it successfully read required things.

示例:

    if (scanf("%4s", select) != 1) {
        fputs("read error\n", stderr);
        exit(1);
    }

另外最好读取要读取的长度以避免缓冲区溢出.在上面的例子中也是这样做的.

Also it is good to read the length to read to avoid buffer overrun. This is also done in the above example.

还有一点是 select == "Yes" 不是在 C 中比较字符串的正确方法.这是比较指针,它不会是真的,因为数组和字符串文字存储在内存中的不同位置.strcmp() 函数来自string.h 用于比较字符串.

One more point is that select == "Yes" is not a correct way to compare strings in C. This is comparing pointers and it won't be true because the array and the string literal are stored in differenct places in memory. strcmp() function from string.h is useful to compare strings.

这篇关于忽略返回值:'scanf'(关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆