473,686 Members | 3,605 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to prevent a letter insert in a int var ?

YUS
Hi,
I've got a problem.

I have a program that ask for a number to the user.
If the user put a letter instead of a number the program crashes (loop).

How can I prevent this ?
I've tried with isdigit but with no results.

int choise;

cout << "\nChoose one: ";
cin >> setw(sizeof(cho ice)) >> choise;
if(isdigit(choi ce)) cout <<"all ok";
if(isalpha(choi ce)) cout<<"error - number needed";

but the code doesn't work.
=(

Thanks to all.

--
oooO Oooo
( ) YUS ( )
\ ( Para todos, todo, ) /
\_ ) nada para nosotros. ( _/
Jan 31 '06 #1
6 5624
* YUS:
I've got a problem.

I have a program that ask for a number to the user.
If the user put a letter instead of a number the program crashes (loop).

How can I prevent this ?
I've tried with isdigit but with no results.

int choise;

cout << "\nChoose one: ";
cin >> setw(sizeof(cho ice)) >> choise;
if(isdigit(choi ce)) cout <<"all ok";
if(isalpha(choi ce)) cout<<"error - number needed";

but the code doesn't work.


Consider that attempted conversion to 'int' has already happened by the
time you call 'isdigit' and 'isalpha'.

Instead check the error state of the stream.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jan 31 '06 #2
YUS
Alf P. Steinbach wrote:
Consider that attempted conversion to 'int' has already happened by
the time you call 'isdigit' and 'isalpha'.

Instead check the error state of the stream.


Sorry but.. how ???
:p
I really got no idea!

--
oooO Oooo
( ) YUS ( )
\ ( Para todos, todo, ) /
\_ ) nada para nosotros. ( _/
Jan 31 '06 #3

YUS wrote:
Alf P. Steinbach wrote:
Consider that attempted conversion to 'int' has already happened by
the time you call 'isdigit' and 'isalpha'.

Instead check the error state of the stream.


Sorry but.. how ???
:p
I really got no idea!


http://www.parashift.com/c++-faq-lit....html#faq-15.2

Gavin Deane

Jan 31 '06 #4

"YUS" <mo******@NOSPA Mtin.it> wrote in message
news:43******** *************** @reader1.news.t in.it...
Hi,
I've got a problem.

I have a program that ask for a number to the user.
If the user put a letter instead of a number the program crashes (loop).

How can I prevent this ?
I've tried with isdigit but with no results.

int choise;

cout << "\nChoose one: ";
cin >> setw(sizeof(cho ice)) >> choise;
if(isdigit(choi ce)) cout <<"all ok";
if(isalpha(choi ce)) cout<<"error - number needed";

but the code doesn't work.
=(


A common solution is to always enter data into a std::string, and then see
if the string can be converted into an integer (or double or whatever). If
it cannot be converted, then tell the user there's an error and loop back to
allow them to re-enter the data.

-Howard

Jan 31 '06 #5

"YUS" <mo******@NOSPA Mtin.it> wrote in message
news:43******** *************** @reader1.news.t in.it...
Hi,
I've got a problem.

I have a program that ask for a number to the user.
If the user put a letter instead of a number the program crashes (loop).

How can I prevent this ?
I've tried with isdigit but with no results.

int choise;

cout << "\nChoose one: ";
cin >> setw(sizeof(cho ice)) >> choise;
if(isdigit(choi ce)) cout <<"all ok";
if(isalpha(choi ce)) cout<<"error - number needed";

but the code doesn't work.
Look again at the documentation for 'isdigit()'.
It doesn't do what you apparently believe.
=(


#include <istream>
#include <iostream>
#include <sstream>
#include <string>

int get_int()
{
int result(0);
std::string text;
std::istringstr eam iss;;

do
{
std::cout << "Enter an integer value: ";
std::cin >> text;
iss.clear();
iss.str(text);

if(!(iss >> result))
std::cerr << " * Not a valid integer value\n";

} while(!iss);

return result;
}

int main()
{
int i(0);

i = get_int();
std::cout << "You entered: " << i << '\n';
return 0;
}

-Mike
Jan 31 '06 #6
YUS
YUS wrote:
Thanks to all.


I repeat, thanks to all guys =)
Very useful.

--
oooO Oooo
( ) YUS ( )
\ ( Para todos, todo, ) /
\_ ) nada para nosotros. ( _/
Jan 31 '06 #7

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

Similar topics

5
15493
by: phil_nospam_schmidt | last post by:
I am trying to prevent a user from resizing a frame beyond its "natural" size as given by winfo_reqwidth and winfo_reqheight, without any success. Can anyone make any suggestions, based on my code below? Thanks! from Tkinter import * class Table(Frame): def __init__(self, master,
3
3064
by: kjaggi | last post by:
I am trying to either write a trigger or a check constraint to prevent duplicates in my table. There are two columns I need to look at for the duplicates and only one combo value for both columns is allowed in the table. For e.g. Column Serial can have only one '123456' value with testresult value as 'PASS'. This serial can be in the table many times with any other combo so for e.g. The table could contain 100 entries for serial column...
1
1601
by: em_lom | last post by:
I have a simplelist of names that I got from the database. I have written all the names from the simple list to the screen. what I'm looking to do is the following: A-H I-P Q-Z anne isabella rachel beth jen steph
4
25168
by: sanjana | last post by:
hi i m using the win32_diskdrive class for detecting a memory card insertion and removal..and this class detects memory card(sd card..etc) insertion removal from the device the deviceid attribute gives me \\.\PHYSICALDRIVE0 or \\.\PHYSICALDRIVE1 etc.. i m trying to get the drive name say(c: or d: ...etc)from the device
1
2505
by: ntuyen01 | last post by:
Hi All, I have this data file with fix length(see below). I am able to insert it into the database using bcp, but now I want to skip (do not insert) the row which start with letter 'S' into the database. Is there away to do it? By the way I am using -F2 option to skip the first record. Here is my data: Record 1 04 XXX 2 13106900240120042003040045061 Testing N POLYDOROS TRUST
3
2955
by: groups2 | last post by:
When you press the down key while in an input field the default behavior for some event creates a dropdown of the previously input text. What event creates that behavior and how do I stop it ? For example, to prevent ANY type of default behavior when clicking ANY key, I thought this would work, but the dropdown still occurs. What am I doing wrong ? In html file:<body onload="registersearch()" >
9
2234
by: Ulterior | last post by:
Hi, everyone, I have a simple problem, which bothers me for some while. I will try to explain it - There is some string, whith different letters in it. Is it possible to analyse this string and the reffer to it knowing that it has some certain letters in it using only some integer value?
3
8914
by: Kalaine | last post by:
MSAccess 2003: Users tab through the data entry fields on a form, and accidently tab to the next record thereby erroneously inserting a record. What can I code in the Form_BeforeInsert to prevent the insert from happening? Private Sub Form_BeforeInsert() If MsgBox("Do you want to save the new BSR record " & Me.BSR_ID & " and all associated offers and price plan?", vbYesNo) = vbNo Then 'What can I code here to prevent the...
6
4544
by: teser3 | last post by:
I have my PHP inserting into Oracle 9i. But how do I prevent duplicate record entries? I only have 3 fields in the insert in the action page: CODE <?php $c=OCILogon("scott", "tiger", "orcl"); if ( ! $c ) { echo "Unable to connect: " . var_dump( OCIError() );
0
8514
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9050
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8932
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8766
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8778
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6439
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4307
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1933
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.