-1

I tried to scan 2 different strings to 2 different elements of the same struct and I don't know why its not working.

This is my code:

struct qRegStudents{
  char studID[6];
  char studName[25];
};

typedef struct qRegStudents students;

int RegStudent() {
  students Student;
  char temp[6];

  printf("Enter ID Number: ");
  scanf(" %6s",Student.studID);
  printf("Enter Name: ");
  scanf(" %25s",Student.studName);

  printf("%s",Student.studID);

  return 0;
}

I input the student ID as "123456" and then the name as "josh". It prints "123456josh" as just the student ID

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 1
    `char temp[6];` _looks_ unused (and hopefully OP is not truly using it somehow). Suggest removing it as its just noise and may contribute to [this](https://stackoverflow.com/questions/50049153/trying-to-scan-strings-to-2-different-elements-of-a-struct-in-c#comment87114717_50049240). – chux - Reinstate Monica Apr 26 '18 at 18:02
  • You might also want to check out this question about multiple scanfs leaving carriage return characters in the buffer: https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer – bruceg Apr 26 '18 at 18:05
  • Also see this https://stackoverflow.com/questions/217074/parsing-input-with-scanf-in-c – Achal Apr 26 '18 at 18:16
  • How are you expecting `printf` to know to print six characters in this line of code: `printf("%s",Student.studID);`? – David Schwartz Apr 26 '18 at 18:29
  • Take the tour, read How to Ask, and Minimal, Complete, and Verifiable example. You do need to leave room in studId for the terminal null character. Test your program with "12345" as the student Id, you'll see that you get the expected behavior. – jwdonahue Apr 26 '18 at 20:07

2 Answers2

3

You didn't allocate enough space in the studID field to hold 6 characters plus the null terminator. Change the definition to:

struct qRegStudents{
    char studID[7];
    char studName[25];
};

Edit... Best to include a \n at the end of the printf string to make sure it gets flushed to stdout.

bruceg
  • 2,433
  • 1
  • 22
  • 29
2

your program have a undefined behavior as there is no memory space you kept for '\0' at the end of studID and studName. Allocate enough memory location.

make it like

struct qRegStudents{
        char studID[7]; /* plus 1 for terminating \0 char at end */
        char studName[26];
};

Also do fflush(stdout) to clear stdout stream or use \n. for e.g

printf("%s\n",Student.studID);
printf("%s\n",Student.studName);

Always compile your code with warning enable flags. For e.g -Wall flag. It will tell you something about unused variable(temp[6]), read it.

Achal
  • 11,821
  • 2
  • 15
  • 37