Link to home
Start Free TrialLog in
Avatar of cookiejar
cookiejarFlag for United States of America

asked on

First character of input string truncated with scanf

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);
  }
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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