-3

I am trying to create a program where the user enters their name and a float number, when the user enters their name it completely skips the part to enter a double I am not sure what is causing this problem the code bellow is what i have:

#include <stdio.h>
#include <stdint.h>

//extern double control(); //name in asm label (ex. global start)

int main()
{
  
   char name[100];
   double salary;
 printf("Welcome to Software Analysis by Paramount Programmers, Inc.\n");
 printf("Please enter your first and last name and press enter: ");
 scanf("%s", name);
 scanf("%lf", &salary); 
 printf("%lf", salary); 
 //printf("%f", var); 
 return 0;

result

Welcome to Software Analysis by Paramount Programmers, Inc.
Please enter your first and last name and press enter: david n
0.000000The bash script file will terminate
sadboy99
  • 45
  • 1
  • 6
  • What bash script file? – tadman Apr 20 '21 at 22:51
  • `%s` stops at the first whitespace. So after the first `scanf` only `david` is consumed. There is still `n` in the input stream which the next `scanf` attempts to and fails to parse. – kaylum Apr 20 '21 at 22:54

1 Answers1

1

As the commentator wrote above, scanf ("%s", str) reads characters from the input stream until a space or '\n ' is encountered. Instead of the above function, use

fgets(name, sizeof(name), stdin)

Good luck :)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
malloc
  • 81
  • 6
  • Never recommend `gets` to anyone. `fgets` is what should be used instead. [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – kaylum Apr 20 '21 at 23:05
  • for example, I know about scanf_s, but may have forgotten about gets. it's late in my country, so my brain isn't working properly. thx for correction – malloc Apr 20 '21 at 23:09
  • And remember that `fgets`, unlike the obsolete `gets`, leaves a `'\n'` in the target array -- *if* it's big enough to hold the whole line. Read the documentation before using it (advice that applies to every library function, not just `fgets`). – Keith Thompson Apr 20 '21 at 23:19
  • @KeithThompson thank you for information about '\n'. i've never debugged string after fgets. thanks again – malloc Apr 20 '21 at 23:25