问题
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