gpt4 book ai didi

c - 如何读取带有空格的scanf

转载 作者:行者123 更新时间:2023-12-02 08:58:56 24 4
gpt4 key购买 nike

我遇到了一个奇怪的问题

我正在尝试使用 scanf() 从控制台读取字符串

像这样

scanf("%[^\n]",string1);

但它没有读取任何内容。它只是跳过整个 scanf。

我正在 gcc 编译器中尝试

最佳答案

尝试使用 scanf 读取带有空格的字符串可能会带来不必要的问题,例如缓冲区溢出和留在输入缓冲区中以便稍后读取的杂散换行符。通常建议使用 gets() 作为解决方案,但是,

来自联机帮助页:

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

因此,不要使用 gets,而是使用 fgets 和 STDIN 流从键盘读取字符串

关于c - 如何读取带有空格的scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com