cguy
February 18th, 2011, 03:31 AM
I want to read floats from the keyboard and display them along the time when they were read.
Upon invalid input or the insertion of a newline the program should terminate.
Here's my code, which does not treat the newline part because I don't know how to do it. Also, when the input is invalid (ie: inserted a letter), the second scanf (at the bottom of the "while") is being skipped and the while condition is evaluated to true, even though scan_ret IS 0.
int scan_ret = scanf("%f", &freq);
while (( scan_ret != 0 ) || ( scan_ret != EOF ))
{
time(now);
now_tm = localtime(now);
/* TODO: replace stdout with f
* TODO: replace \n with \t
*/
if ( fprintf(stdout, "%.3f %d:%d:%d\n", freq, now_tm->tm_hour,
now_tm->tm_min, now_tm->tm_sec) < 0)
{
fprintf(stderr, "Could not write to file. Exiting.");
exit(EXIT_FAILURE);
}
scan_ret = scanf("%f", &freq);
}
So what's wrong with it and how can I fix it?
Also, which is the "proper" way to read an unknown number of numbers from the keyboard until newline/a letter is entered?
Thanks!
Upon invalid input or the insertion of a newline the program should terminate.
Here's my code, which does not treat the newline part because I don't know how to do it. Also, when the input is invalid (ie: inserted a letter), the second scanf (at the bottom of the "while") is being skipped and the while condition is evaluated to true, even though scan_ret IS 0.
int scan_ret = scanf("%f", &freq);
while (( scan_ret != 0 ) || ( scan_ret != EOF ))
{
time(now);
now_tm = localtime(now);
/* TODO: replace stdout with f
* TODO: replace \n with \t
*/
if ( fprintf(stdout, "%.3f %d:%d:%d\n", freq, now_tm->tm_hour,
now_tm->tm_min, now_tm->tm_sec) < 0)
{
fprintf(stderr, "Could not write to file. Exiting.");
exit(EXIT_FAILURE);
}
scan_ret = scanf("%f", &freq);
}
So what's wrong with it and how can I fix it?
Also, which is the "proper" way to read an unknown number of numbers from the keyboard until newline/a letter is entered?
Thanks!