[Wylug-help] C++ code

Philip Wyett philipwyett at dsl.pipex.com
27 Oct 2002 23:59:15 +0000


--
On Sun, 2002-10-27 at 22:27, Roger Greenwood wrote:
> I need a bit of help trying to convert some old code I wrote (originally
> for DOS in 1995) into Linux.
>
> If you don't do C/C++ programming stop reading now as this is going to
> be boring.
>
> The problem is buffers (i think). The code snippet following gets a
> number from stdin, by way of any string entry. The commented out bits
> have been left in so you can see where I am.
>
> What happens is that the number entered seems to leave an entry in the
> buffer so that the next question is already answered (incorrectly).
>
> All comments appreciated.
>
> If you want the full code you can have it.
>
> int getnum(void)
> {
> 	int num;
> 	double numd;
> 	char entry[80];
> 	int valid = FALSE;
> 	int exit = FALSE;
> 	double dummy = 0;
> 	double fraction;
> 	do
> 	{
> 		//gets(entry);  note gets is not safe!!
> 		//cin >> setw(5) >> entry;
> 		//scanf("%5s",entry);
> 		fgets(entry,5,stdin);
> 		numd = atof(entry);
> 		fraction = modf(numd,&dummy);
> 		//cout << "\n\n  Getnum debug :-";
> 		//cout << "\n\n  Entry = "<<entry;
> 		//cout << "\n  numd = "<<numd;
> 		//cout << "\n  fraction = "<<fraction;
> 		//cout << "\n  dummy = "<<dummy<<"\n\n";
> 		if (fraction !=0)
> 		{
> 			cout <<"\nEntry must be a whole number - decimals not allowed ";
> 			numd = -1;
> 			cout <<"\n\nPlease try again :- ";
> 		}
> 		if (numd == 0) exit = TRUE;
> 		if (numd >0)
> 		{
> 			if (numd <= MAXINT)
> 			{
> 				valid = TRUE;
> 			}
> 			else
> 			{
> 				cout << "\nEntry must be less than "<< MAXINT;
> 				cout << "\n\nPlease try again :- ";
> 			}
> 		}
> 	}
> 	while ((valid == FALSE) && (exit == FALSE));
> 	if (exit == TRUE)
> 	{
> 		num = 0;
> 	}
> 	else
> 	{
> 		num = int(numd);
> 	}
> 	return(num);
> }
>
>
> Roger Greenwood.
>
> --
> The trouble with doing something right the first time is that no one
> appreciates how difficult it was.
>
> _______________________________________________
> Wylug-help mailing list
> Wylug-help@wylug.org.uk
> http://list.wylug.org.uk/mailman/listinfo/wylug-help

Hi,

fflush(stdin); may help you once input has been taken and it's contents
can be safely dumped. I would suggest you look at the whole code as it
is hybrid and never much welcomed by many, especially C++ coders.

Regards

Philip Wyett

--

Key pair can be obtained using the link below.

http://www.philipwyett.dsl.pipex.com/PhilipWyett.asc

--
--
Content-Description: This is a digitally signed message part

[ signature.asc of type application/pgp-signature deleted ]
--