I'm taking an entry level C++ programming course and I'm totally stuck on this last homework assignment. You're supposed to take an unsigned integer into a variable of type unsigned short int. I'm not allowed to use "cin >>" inside the program.
Everything works with my code, it just doesn't output the correct answer. If the user inputs a number, its supposed to output the number. However, I only get the first digit. I skip the white spaces and give an error if user inputs a character, but when everything is okay I get hung up during my last while statement.
Code:
// Name: David Hart
// Date: 04/07/2010
// Class: C101 MW 3:00
// Homework#: Ten
// Source File: HW10problem1.cpp
// Action: Recreate the extraction operator.
#include <iostream>
#include <ctype.h>
using namespace std;
int ReadInt(unsigned short int&);
void main ()
{
char Continue;
unsigned short int UserInput = 0;
int Error;
do
{
cout << "This program will immitate the extraction operator as used on integers." << endl;
Error = ReadInt(UserInput);
if (Error == 1)
cout << "Error code 1: Please enter a number, not a character.";
else if (Error == 2)
cout << "Error code 2: The number must be less than 65535.";
else if (Error == 0)
cout << UserInput;
cin.putback(UserInput);
cin.ignore (100, '\n');
cout << "\n\nWould you like to continue? N or n to stop ==> ";
cin >> Continue;
cin.putback(UserInput);
cin.ignore (100, '\n');
UserInput = 0;
}
while
((Continue != 'N') && (Continue != 'n'));
}
int ReadInt(unsigned short int &UserInput)
{
char ch;
cout << "\nEnter a number ==> ";
cin.get(ch);
while (ch == ' ')
ch = cin.get();
if (isdigit(ch) == 0)
return 1;
while (isdigit(ch) == 1)
ch = cin.get();
int X = ch - '0';
if ((ch * 10) + X > 65535)
return 2;
else
UserInput = UserInput * 10 + X;
cout << UserInput;
return 0;
}
Thanks in advance for any help and sorry if its confusing : /