473,320 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Validating keyboard input

The following 'book example' of validating input seems to be incomplete.
Since it is a beginner's book it may be intentional for simplicity. But
I would like to know how to make this program work for all invalid
input. Just for example, if user inputs 'abc' an error is caught, but if
user inputs '432' the program hangs. Any clarification appreciated.

Thanks,

Bill
#include <stdio.h>

int main(void)
{
float temp_i, temp_o;
char which_i, which_o;
char junk;

printf("Enter a temperature and indicate\n");
printf("if it's Fahrenheit or Celsius [##.# C/F]: ");
if (scanf("%f %c", &temp_i, which_i) == 2)
{
switch (which_i)
{
case 'C':
case 'c':
temp_o = (temp_i * (9.0/5.0)) + 32;
which_o = 'F';
break;

case 'F':
case 'f':
temp_o = (temp_i - 32) * (5.0/9.0);
which_o = 'C';
break;

default:
which_o = 0;
break;
}
if (which_o)
{
printf("%0.1f %c is %0.1f %c.\n",
temp_i, which_i, temp_o, which_o);
}
else
{
printf("You failed to enter C or F.\n");
}
}
else
{
printf("You failed to use the proper syntax.\n");
}

do {
junk = getchar();
} while (junk != '\n');

getchar();

return 0;
}
Nov 15 '05 #1
2 5175

"bildad" <bi****@wi.rr.com> wrote
The following 'book example' of validating input seems to be incomplete.
Since it is a beginner's book it may be intentional for simplicity. But I
would like to know how to make this program work for all invalid input.
Just for example, if user inputs 'abc' an error is caught, but if user
inputs '432' the program hangs. Any clarification appreciated.

Thanks,

Bill
#include <stdio.h>

int main(void)
{
float temp_i, temp_o;
char which_i, which_o;
char junk;

printf("Enter a temperature and indicate\n");
printf("if it's Fahrenheit or Celsius [##.# C/F]: ");
if (scanf("%f %c", &temp_i, which_i) == 2)
{
switch (which_i)
{
case 'C':
case 'c':
temp_o = (temp_i * (9.0/5.0)) + 32;
which_o = 'F';
break;

case 'F':
case 'f':
temp_o = (temp_i - 32) * (5.0/9.0);
which_o = 'C';
break;

default:
which_o = 0;
break;
}
if (which_o)
{
printf("%0.1f %c is %0.1f %c.\n",
temp_i, which_i, temp_o, which_o);
}
else
{
printf("You failed to enter C or F.\n");
}
}
else
{
printf("You failed to use the proper syntax.\n");
}

do {
junk = getchar();
} while (junk != '\n');

getchar();

return 0;
}


The problem is that scanf() eats whitespace, so the newline is consumed if
you enter a valid number, but not if you enter alphabetical characters
(because the function stalls on the first non-digit).

Then the program hits the getchar() lines, because only one field has been
converted. I suspect it won't hang if you enter a few characters.

It's not well written, but scanf() is a hard function to use in a solid
fashion. In production code you would probably call a line gobbling function
(fgets has its own problems) and then use sscanf().
Nov 15 '05 #2
bildad <bi****@wi.rr.com> writes:
The following 'book example' of validating input seems to be
incomplete. Since it is a beginner's book it may be intentional for
simplicity. But I would like to know how to make this program work for
all invalid input. Just for example, if user inputs 'abc' an error is
caught, but if user inputs '432' the program hangs. Any clarification
appreciated.


It doesn't really hang; it just waits for you to input a
non-whitespace character.
#include <stdio.h>


int main(void)
{
float temp_i, temp_o;
char which_i, which_o;
char junk;

printf("Enter a temperature and indicate\n");
printf("if it's Fahrenheit or Celsius [##.# C/F]: ");
if (scanf("%f %c", &temp_i, which_i) == 2)


The format string consists of 3 directives:

"%f" reads a number in floating-point format.

" " reads input up to the first non-whitespace character.

"%c" reads a single character, which may or may not be whitespace.

So if the user types "432" followed by a newline, the "%f" consumes
the "432", and the " " consumes the newline (and any whitespace
following it). As soon as the user types a non-whitespace character
(such as 'F' or 'C'), the scanf() will consume it and finish.

Or rather, it would if the third argument to the scanf() call were
correct. Given the "%c" directive, the corresponding argument needs
to be a pointer-to-char; you've given it a char. Change "which_i" to
"&which_i".

For better error handling, if you want to require all the input to be
on one line, you can use fgets() to read the entire line, then use
sscanf() to validate and parse it. sscanf(), unlike scanf(), fails
immediately if the input is incomplete, rather than waiting for more
input to appear.

You should also handle the case of fgets() reading an incomplete line.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: The Plankmeister | last post by:
Hi... What's the best method of validating input characters? I would like to prevent users submitting exotic characters (such as those acquired on Windows Systems by pressing ALT+) and thought...
0
by: Ray | last post by:
I have English Windows XP Pro and Office 2003 Pro on my computer. When I enter data into fields of tables, queries and forms of Access 2003, it automatically switches to Chinese keyboard input. ...
7
by: Don Riesbeck Jr. | last post by:
I'm working on an application (OEM) using C# that utilizes input from a keyboard, and USB Barcode Scanner. The scanner is a HID Keyboard device, and input from it is sent to the system as if it...
1
by: panche | last post by:
I'm developing a fairly simple user control that has two textboxes for date/time entry (a from date/time and a to date/time). One of my requirements is that there should be no button that sets...
0
by: rs | last post by:
Hi guys, I am trying to read from a USB keyboard using vb.net and HID classes. the USB keyboard is not my primary keyboard. I have a ps2 keyboard connected and is detected in device manager as...
2
by: rs | last post by:
Hi guys, I am trying to read from a USB keyboard using vb.net and HID classes. the USB keyboard is not my primary keyboard. I have a ps2 keyboard connected and is detected in device manager as...
0
by: Matthew | last post by:
All, I have searched google and the newsgroups but can't find anything the same as what I am experiencing (though I may have missed something). I have controls (textboxes) within UserControls...
9
by: chuck | last post by:
I need some help with validating user input. I am writing a C computer program for an intro to C course. Here is the situation. I am creating an application that will do currency conversions. ...
8
by: BD | last post by:
How can I duplicate the behavior of the operating system shortcut keys in my application? For example, my windows form has 5 controls (textboxes), the operating system will pickup which control...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.