1

Code contains a structure which contains two data member mtype and mtext, MAXSIZE is the maximum size of that variable. I want to insert data into mtext. I have the code also, but I don,t know how scanf("%[^\n]",sbuf.mtext); here is working. And if there is any other method to do so, then please tell me.

struct msgbuf{
    long    mtype;
    char    mtext[MAXSIZE];
}sbuf;

scanf("%[^\n]",sbuf.mtext);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    Answer to 2nd question: http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c – 001 Sep 10 '15 at 19:55

1 Answers1

2

scanf("%[^\n]",sbuf.mtext);

  1. Fails to scan anything into sbuf.mtext if the first character is '\n'. scanf() returns 0.

  2. Scans endless number of characters into sbuf.mtext until a '\n' is encountered and left in stdin and then appends a '\0'. Buffer overrun possible. scanf() returns 1 if an overrun did not occur. If an overrun occurs, it is undefined behavior.

  3. Better to use fgets() to read user lines of input.

    if (fgets(sbuf.mtext, sizeof sbuf.mtext, stdin) == NULL) Handle_EOF();
    sbuf.mtext[strcspn(sbuf.mtext, "\n")] = '\0';  // drop potential \n
    
  4. "And why we don't use '&' before 'var' as we do for %d or %f?" One question at a time.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256