2

i'm recently start to learning C because i start a course in my university. In one of my lesson I need to write a program that converts a number of in ms to days, hours, minutes, second and milliseconds. I use this source code:

#include <stdio.h>

int main ()
{
long int time_ms;
int d, h, m, s, ms;
printf("insert the value in ms: \n");
scanf("%ld\n", &time_ms);

d = time_ms/(24*60*60*1000); //ms in a day
time_ms = time_ms%(24*60*60*1000); //reminder in ms

h = time_ms/(60*60*1000);
time_ms = time_ms%(60*60*1000);

m = time_ms/(60*1000);
time_ms = time_ms%(60*1000);

s = (time_ms/1000);
ms = time_ms%1000;

printf("%d d %d h %d m %d s %d ms\n",
         d,   h,   m,   s,   ms);
}

i compling it, and it work, but after i insert the number of milliseconds the shell of MacOs (were i'm working) doesn't print anything until i type "exit". what do i wrong?

dbush
  • 205,898
  • 23
  • 218
  • 273

2 Answers2

3

Here's your problem:

scanf("%ld\n", &time_ms);

You have a \n in your sequence. That means that after entering a number and pressing enter, scanf reads the number, then reads the newline, then is waiting for something that isn't a newline before returning.

Remove the newline character from the format string:

scanf("%ld", &time_ms);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • That is going to lead OP headlong into the _other_ canonical scanf headache, where it leaves the trailing newline on the input buffer and the _next_ read misbehaves. Better you should recommend `fgets` + `sscanf` or `strtol`. – zwol Mar 16 '18 at 11:29
  • ok thankyou dbush i resolved removin "\n" from scan. i will learn next in the course the other function. thank you – acidwinzip 77 Mar 16 '18 at 14:07
2

You have made one of the classic mistakes: you used scanf. There are a whole bunch of reasons not to use scanf ever, but right now the important reason is that scanf("%d\n") is going to keep trying to read input after the number, until it receives either EOF or something that isn't whitespace.

What you want to do instead is use fgets, which will read one entire line of input no matter what its contents are, and then sscanf to parse the number. When you start writing more sophisticated programs you'll discover that even sscanf is troublesome and it's better to use lower-level functions like strtol and strsep, but for a classroom exercise like this sscanf is fine.

zwol
  • 135,547
  • 38
  • 252
  • 361