YankeeWhiskey
YankeeWhiskey

Reputation: 1582

scanf() goes without taking any input

I have C code doing some calculations (irrelevant to my question, I believe ). The program will ask for some parameters for calculation. The problem is when I running the codes, a scanf("%c", &ch) isn't working properly.

I'm interested in whether you can reproduce this problem because it seems that I didn't get anything wrong, am I?

I posted an compilable and shortened version of my program.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
        float Dia_MM, Dia_I, Se1, Se, Sut = 75.00;
        float Ka, Kb, Kc, Kd, Ke, Kf;
        char Ch;
        char Bt;
        float Reli;
        printf("Please input the surface condition of the shaft: G, M, H or A\n");
        scanf("%c", &Ch);
//      getchar();
        printf("Please input the diameter of the shaft in inch\n");
        scanf("%f", &Dia_I);
        printf("Please specify whether your shaft is in bending (B) or torsion (T)");
        scanf("%c", &Bt);// THIS LINE IS JUST SKIPPED
        exit(0);
}

The GDB log is listed:

  Breakpoint 1, main () at main.c:25
  25        float Dia_MM, Dia_I, Se1, Se, Sut = 75.00;
  (gdb) n
  30        printf("Please input the surface condition of the shaft: G, M, H or A\n");
  (gdb) n
  Please input the surface condition of the shaft: G, M, H or A
  31        scanf("%c", &Ch);
  (gdb) G
  Undefined command: "G".  Try "help".
  (gdb) n 
  G
  33        printf("Please input the diameter of the shaft in inch\n");
  (gdb) n
  Please       input the diameter of the shaft in inch
  34        scanf("%f", &Dia_I);
  (gdb) n
  4.5
  35        printf("Please specify whether your shaft is in bending (B) or torsion (T)");
  (gdb) n
  36            scanf("%c", &Bt);
  (gdb) n                            //PROBLEM HERE. SCANF() GOES BEFORE TAKE ANY INPUT.
  37        exit(0);

Upvotes: 3

Views: 4307

Answers (3)

User170496
User170496

Reputation: 7

You can also use

scanf(" %c",&c);

Upvotes: 0

Manolis Ragkousis
Manolis Ragkousis

Reputation: 665

As thkala told above scanf() does not consume trailing newlines.But there is another way to absorb the newline from the previous line using \n like that scanf("%c\n",...).

Upvotes: 4

thkala
thkala

Reputation: 86353

scanf() does not consume trailing newlines. The skipped scanf() receives the newline from the previous line typed by the user and terminates without receiving more input as you would expect...

scanf() is a bit cumbersome with newlines. A possible solution would be to use fgets() to get a line from the console and then employ sscanf() to parse the received string.

Another, more targeted, solution would be to use " %c" in the format string of the last scanf() call. The %c format specifier does not consume leading whitespace on its own, which is why it gets the remaining newline, rather than a character typed by the user.

Upvotes: 5

Related Questions