Home > Software design >  Scanf not reading first character
Scanf not reading first character

Time:08-27

I have this, when I put the function in main the input is 'hello' and the output is 'ello'.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void getString() {
     char enter;
     printf("Type input below"); 
     scanf("%c", &enter);
     system("cls");
}

void scanString () {
     char target[100];
     scanf("%s", &target);
     printf("%s", target);
}

int main () {
     getString();
     scanString();
}

CodePudding user response:

Your getString is explicitly eating a single character from stdin with scanf("%c", &enter) and ignoring it, so the second scanf in scanString doesn't receive that character. From the names used, it seems like you think you're consuming a newline the user already put in stdin, but in fact, the user is not entering a newline, they just enter hello, and you consume and discard the h, clear the screen, then consume and print the ello.

CodePudding user response:

void getTarget () {
     char target[100];
     printf("Type input below and press ENTER");
     scanf("           
  • Related