[Wylug-help] C++ code

Roger Greenwood rg at nthong.freeserve.co.uk
Sun, 27 Oct 2002 22:27:08 +0000


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.