First character of input string truncated with scanf

cookiejar
cookiejar used Ask the Experts™
on
Using scanf, with my initial prompt for input , the first character of the input string is truncated.

For example, if I enter George,  only eorge is accepted from the keyboard.  This only occurs on the first scanf.  What am I doing wrong?  See code below.

 /*  Prompt for initial input  */
  printf("\n Enter a student name (First Last) or (0) to Exit : ");
  fflush(stdin); getchar();
  scanf("%14[^\n]s", studentName);


  while (studentName[0] != '0')
  {
    studentCount++;


    fprintf(rpt, "\n %-18s %6.2f %18c", studentName, percentGrade, letterGrade);

    printf("%s", studentName);
    printf("\n Enter a student name (First Last) or (0) to Exit : ");
    fflush(stdin); getchar();
    scanf("%14[^\n]s", studentName);
  }
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2014
Top Expert 2015
Commented:
It looks like the getchar(); is getting the G character.
Sinisa VukSoftware architect
Top Expert 2012

Commented:
ozo is right.You want to get Name or 0 for exit with getchar - but first char of (G)eorge was get.
Better:
 do {    
    printf("\n Enter a student name (First Last) or (0) to Exit : ");
    fflush(stdin); 
    scanf("%14[^\n]s", studentName);

    if (studentName[0] != '0')
    {
         studentCount++;
...
         fprintf(rpt, "\n %-18s %6.2f %18c", studentName, percentGrade, letterGrade);
         printf("%s", studentName);
....
    }
  } while (studentName[0] = '0')

Open in new window

Top Expert 2016

Commented:
you better use gets for user input instead of scanf.

the user would terminate each input by enter.

char szInput[512] = { '\0' }:
...
if (!gets(szInput)) return -1;
strncpy(studentName, szInput, min(14, strlen(szInput));

...
if (!gets(szInput)) return -1;

Open in new window

studentAge = atoi(szInput);

using gets has the advantage that you don't need care so much for the stdin input stream which behaves strange (especially on windows) with text input. also it is not so easy for the user to spoil the stdin what would prevent from further input until the stdin was not reset.

Sara

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial