如何在 C 中获取包含 space 而没有 gets() 的字符串?
How to get strings containing space without gets() in C?
当使用 scanf()
获取包含 space 的字符串时,它仅分配 space 之前给出的输入。就像我给 "hello world" 作为输入一样。只有 "hello" 存储在变量中。我知道 scanf()
很自然。当我使用 gets()
时,它工作正常。但 gcc 报告说 gets()
已被弃用。它还会发出警告,指出 gets()
是危险的,不应使用。那么没有 gets()
如何获得带有 space 的字符串?还有其他替代功能吗?
您可以使用char *fgets(char *str, int n, FILE *stream)
要从用户那里获取输入,而不是 FILE* stream
,请使用标准输入 stdin
fgets (str, 60, stdin)
当使用 scanf()
获取包含 space 的字符串时,它仅分配 space 之前给出的输入。就像我给 "hello world" 作为输入一样。只有 "hello" 存储在变量中。我知道 scanf()
很自然。当我使用 gets()
时,它工作正常。但 gcc 报告说 gets()
已被弃用。它还会发出警告,指出 gets()
是危险的,不应使用。那么没有 gets()
如何获得带有 space 的字符串?还有其他替代功能吗?
您可以使用char *fgets(char *str, int n, FILE *stream)
要从用户那里获取输入,而不是 FILE* stream
,请使用标准输入 stdin
fgets (str, 60, stdin)