HossTheGreat
Technical User
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 << "Enter an integer:";
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 << "You entered a valid value\n";
cout << userValue << endl;
}
else
{
// The string is invalid
cout << "You entered an invalid value\n";
}
return 0;
}
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 << "Enter an integer:";
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 << "You entered a valid value\n";
cout << userValue << endl;
}
else
{
// The string is invalid
cout << "You entered an invalid value\n";
}
return 0;
}