Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Determining

Status
Not open for further replies.

HossTheGreat

Technical User
Nov 6, 2003
7
0
0
US
Ok, I've been working on a project for school. We're supposed to be taking char input from a user, examining whether or not it is a valid integer and then converting it from char to int. I've got it working within the main function, however I need this to be a seperate function. I was given the following function prototype to use:

Use the following prototype for the function:
bool ReadInt(int *value);

Below is how I have it working thus far. I'm just a little stumped on the other part.

#include <iostream.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
char userText[30];
int userValue;
bool bValid;
unsigned int i;

cout << &quot;Enter an integer:&quot;;

cin.getline(userText,30);

bValid = true;

// Check for minus sign
if (userText[0] == '-')
{
// There was one, there must be at least
// two characters, or it is invalid
if (strlen(userText) < 2)
{
bValid = false;
}
}
else
{
// No minus sign, let's make sure it starts
// with a digit
if ((userText[0] < '0') || (userText[0] > '9'))
{
bValid = false;
}
}

// Check all the other characters to make sure
// that they are all digits
for (i = 1; i < strlen(userText); i++)
{
if ((userText < '0') || (userText> '9'))
{
bValid = false;
}
}

// See if there were any errors
if (bValid)
{
// There were no errors
userValue = atoi(userText);
cout << &quot;You entered a valid value\n&quot;;
cout << userValue << endl;
}
else
{
// The string is invalid
cout << &quot;You entered an invalid value\n&quot;;
}

return 0;
}

 
bool ReadInt(int *userValue)
{
// paste here your code from the main() with the following modif
// 1. Remove int userValue;
// 2. Replace userValue = atoi(userText);
// by *userValue = atoi(userText);
// 3. Replace return 0; by return bValid;
// 4. Get out cout for message

}

How to call ?

int main ()
{
//
int iVal=0;
bool bValid = ReadInt(&iVal);
if (bValid)
{
cout << &quot;You entered a valid value\n&quot;;
cout << userValue << endl;

}
else
{
// The string is invalid
cout << &quot;You entered an invalid value\n&quot;;
}
//
}

-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top