sujeesh
sujeesh

Reputation: 49

Reading a string until press enter key or within array bounds

I want to read a string through keyboard to avoid buffer overflow. When i used fgets(text,30,stdin), it reads but it also reads '\n' character. But i don't want to read '\n' character.

Upvotes: 2

Views: 7144

Answers (3)

iCoder
iCoder

Reputation: 476

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

a little explain:

%30[^\n]

30 which means read at most 30 chars, [^\n] which means read any char except '\n'.

Upvotes: 2

unwind
unwind

Reputation: 399881

So remove the line feed once you have the string:

int get_line(char *buffer, size_t max)
{
  if(fgets(buffer, max, stdin) == buffer)
  {
    size_t len = strlen(buffer);
    if(len > 0 && buffer[len - 1] == '\0')
      buffer[--len] = '\0';
    return len;
  }
  return 0;
}

UPDATE: Changed to return the length, which might save the caller some trouble. This means that for an empty string input, it will return 0.

Upvotes: 1

pmg
pmg

Reputation: 108938

Read with the '\n' character but remove it afterwards

if (fgets(text, 30, stdin)) {
  size_t tlen = strlen(text);
  if (len > 0) {
    if (text[tlen - 1] == '\n') {
      text[--tlen] = 0;
    } else {
      /* fgets read all it could
      ** but there wasn't a '\n'
      ** for the number of bytes available */
    }
  } else {
    /* empty string read: not even a '\n' */
  }
} else {
  /* fgets failed */
}

Upvotes: 0

Related Questions