Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
in C how do I prevent the input of the wrong data type?
I'm new to programing and I was wondering how to keep the user from entering a char data type when I ask for a float value? For example I ask the user to input a number and if they enter a letter the program ends. How do I prevent this? Or check for it in the program without it just ending?
3 Answers
- Tizio 008Lv 71 decade agoFavorite Answer
read the input as string (not scanf with %d or whatelse) and do your check by yourself (check if it is a float number, i.e. it fits the syntax
[-|+]D[.D] or [-|+].D
[-|+] starting optional minus or (|) plus sign
followed by one or more Digits, optionally followed by a dot and another sequence of digits, or -/+ optional followed by a dot and a sequence of digits...
or something like this...
but if you want to "avoid" the user can press a letter and see it like a understand input... you can not use simply the getchar or scanf function, since you need some kind of control on the keypressing event in the console.
this can depend on what operating system you're programmin in.
- Anonymous1 decade ago
If you write in C, you read the input into a string. If you expect a number, use the sscanf() to parse a number. sscanf() returns the number of matches, so if sscanf(mystring, "%d", &ival) returns zero, there is no number in the input. Instead of terminating the program, you should provide an error message like Error: number expected, 'xxx' found where xxx is the string entered by the user. This is an area where you want to be careful about buffer overflow!
- Anonymous5 years ago
Instead of constructing a double to cin you're going to ought to create a string. The string will learn in with cin and you'll seem at each man or woman that's within the string for non-numeric characters. Once you're making the verify you're going to ought to convert the string quantity right into a decimal importance on your double variable.