简体   繁体   English

C-strcmp无法与scanf()一起使用

[英]C - strcmp won't work with scanf()

I am trying to use scanf() with strcmp. 我试图将scanf()与strcmp一起使用。 However, it doesn't work. 但是,它不起作用。 I've included the right header files. 我已经包含了正确的头文件。 I've tried out gets(). 我已经尝试过gets()。 It works but I don't want to be vulnerable of a buffer overflow attack. 它可以工作,但我不想受到缓冲区溢出攻击的攻击。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    char a[100] = "Hello World!";
    char b[100];

    scanf("%s", &b);

    if(strcmp(a, b) == 0) {
        printf("This should work!\n");
    }
}

I compile the program. 我编译程序。 Then, type Hello World! 然后,键入Hello World! into the program. 进入程序。 It won't show the message. 它不会显示该消息。 Also, why does strcmp() show me all kinds of return values? 另外,为什么strcmp()向我显示各种返回值?

Please help. 请帮忙。

Reading the manual on scanf -- you will see that it stops scanning a %s at the first whitespace found 阅读有关scanf的手册-您会发现它在找到的第一个空白处停止扫描%s

scanf("%s", b);

of Hello World 你好世界

will give you Hello but not Wolrd 会给Hello但不会给你Wolrd

Also note that scanf is equally vulnerable to buffer overflow, as you are still not limiting the size of the input in %s -- to limit the input you should probably try to do %99s making sure that you are not reading more than your 100 byte buffer still leavng space for your null termination. 还要注意,scanf同样容易受到缓冲区溢出的影响,因为您仍未以%s限制输入的大小-要限制输入,您可能应该尝试执行%99s以确保读取的读数不超过100字节缓冲区仍为您的空终止留有空间。

As per this question you need something like 根据这个问题,你需要像

scanf("%[^\n]",str)

to read everything up to the newline, and combining that with a length restrction, you would need something like 要阅读换行符之前的所有内容,并将其与长度限制结合起来,您将需要

scanf("%99[^\n]",str)

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

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