### 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.

 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 #include #include #include 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.

 12 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,
 12345 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.