Aziz Ahmed
Aziz Ahmed

Reputation: 81

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

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

Upvotes: 3

Views: 331

Answers (1)

chux
chux

Reputation: 154218

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.

Upvotes: 3

Related Questions