且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C中具有领先空格的stdin获取字符串输入?

更新时间:2023-11-13 19:16:34

要获取用户输入的,请使用 fgets().

To get a line of user input, use fgets().

#define S_MAX_LENGTH
char s[S_MAX_LENGTH + 2];
if (fgets(s, sizeof s, stdin)) {
  s[strcspn(s, "\n")] = '\0'; // Should code want to lop off a potential trailing \n
  ....


请勿使用 scanf(%[^ \ n] s",s); gets(s); .它们遭受缓冲区溢出和其他问题的困扰.


Do not use scanf("%[^\n]s", s); nor gets(s);. They suffer from buffer overflow and other issues.