Avatar of cookiejar
cookiejar
Flag 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);
  }
C

Avatar of undefined
Last Comment
sarabande

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ozo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Sinisa Vuk

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

sarabande

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
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck