..hey guys, my code is below. The specific problem I am having is with line 14, the j = atoi (x[i]); statement in the for loop. The compile error I'm getting says: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *' Not sure if I should be using a pointer here, or what? Any info appreciated...heres the entire code...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//this program sums digits entered by user
#include <iostream>
usingnamespace std;
int main()
{
int sumNums = 0;
int j = 0;
char* strPtr = 0;
char x[5];
cout << "Enter some numbers, and I'll add them up...";
cin >> x;
for(int i=0; i<5; i++){
j = atoi (x[i]);
j += sumNums;
}
cout << sumNums << endl;
}
it says to change an int to a char do the following: 5 + '0';
it had to do with the fact that the minesweeper table was an array of chars. and we had to call a near miss function that return how many mines were near it and it returned an integer that we were supposed to display in that position(which is a char) so we had to take the number returned and add '0' then input it into that positon.
The OP says string element to int and atoi does that with C strings ( http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/ )
Converting a character to a integer is not the same thing - as a character is already an integer - n+'0' converts a single digit integer into its ASCII representation
...thanx for all the replies. I rewrote this with stringstream, but still not working. I am not getting any compile errors, but line 14 is returning 0. What am I missing?
For example, '2' - '0' subtracts the ASCII values of the two digits: 50 - 48 which returns the numerical value of that digit ( 2 )
If you enter less than 4 digits, loop until strlen(x)