atoi function problem using it on part of an array

In this program I'm writing I have the user enter an ID (4 characters long), first two characters are upper case letters and last two are digits with sum less than or equal to ten. In order to do the sum, I'm trying to use atoi function to convert ID[2] and ID[3] to ints. Can I use atoi in this manner? If not any suggestions on how to work around it?

I commented where atoi problem is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64


#include <iostream>
#include <cstring>
#include <cctype>

using namespace std;

char* getEmployeeID (char [5]);

int main ()
{
	char ID [5];

	getEmployeeID(ID);

	cout << "Your ID is: " << ID << endl;

	return 0;
}

char* getEmployeeID (char ID [5])
{
	char * p = ID;
	bool valid = true;	
	int i = 0;
	int j = 2;

	do
	{
		cout << "Enter an employee ID: " << endl;
		cin.getline(ID, 4);

		while (valid && i<1) // checks if first two are uppercase characters
		{
			if (!isupper(ID[i]))
			{
				valid = false;
				cout << "Incorrect ID, please try again." << endl;
			}
			else
				i++;
		}	

		//atoi
		int i1 = atoi(ID[2]);
		int i2 = atoi(ID[3]);
		int sum = i1 + i2; 

		while (valid && j<3) // checks if last two are digits with sum <= 10
		{
			if (!isdigit(ID[j]) && (sum > 10))
			{
				valid = false;
				cout << "Incorrect ID, please try again." << endl;
			}
			else
				j++;
		}

	} while (valid);
	
	return p;
}
Last edited on
The best way to take a single digit number individually from a string would probably be subtracting the decimal equivalent of '0' from its decimal value.

Ascii numbers in a string have decimal equivalents of 48 ('0') through 57 ('9'). Subtracting '0' (dec 48) from, for example, '5' (dec 53) would yield 5 as a decimal.

1
2
const char* str = "15212";
int five = str[1] - '0';


http://www.asciitable.com/index/asciifull.gif
I would still like to use the atoi function somehow still
The atoi() function needs a character string, so you would have to take the digit you are interested in and turn it into a string, basically by putting it in an array with a null terminator,
1
2
3
4
5
    char ID[] = "AB57";
    char work[2];
    work[0] = ID[2];
    work[1] = 0; // null terminator
    int num = atoi(work);

though I'd still go along with the previous suggestion and simply do:
 
    int num = ID[2] - '0';


Topic archived. No new replies allowed.