How to get a string input from stdin that has leading white space in C?

送分小仙女□ 提交于 2021-02-05 05:51:06

问题


Need a solution to get input string start with spaces?

I know a method to include space in input

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

But its working only for space between words. I need a solution for string starts with spaces. And I also need the starting spaces in the variable


回答1:


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
  ....

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



来源:https://stackoverflow.com/questions/60266923/how-to-get-a-string-input-from-stdin-that-has-leading-white-space-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!