如何读取用空格scanf函数 [英] how to read scanf with spaces

查看:449
本文介绍了如何读取用空格scanf函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题。

我试图从控制台读取scanf函数的字符串()

i'm trying to read a string from a console with scanf()

像这样

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

但它不读什么。它只是跳过整个scanf函数。

but it doesnt read anything. it just skips the entire scanf.

我想它gcc编译

推荐答案

尝试使用 scanf函数来读取空格的字符串可以带来和保持缓冲区溢出不必要的问题流浪换行符在输入缓冲器中稍后读取。 获得()通常建议作为解决这一点,但是,

Trying to use scanf to read strings with spaces can bring unnecessary problems of buffer overflow and stray newlines staying in the input buffer to be read later. gets() is often suggested as a solution to this, however,

从手册页:

不要使用gets()函数。因为它是
  不可能知道不知道
  提前数据多少个字符
  得到()将读取,而且因为得到()
  将继续存储字符过去
  缓冲区的末端,这是非常
  危险使用。它已被用于
  打破电脑的安全性。使用与fgets()
  来代替。

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.

因此​​,而不是使用获得,使用与fgets 通过STDIN流从键盘读取字符串

So instead of using gets, use fgets with the STDIN stream to read strings from the keyboard

这篇关于如何读取用空格scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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