0
string typeVisa (string str); int main(){ string credit_card; string type; getline(cin, credit_card); type = typeVisa(credit_card); } string typeVisa (string str){ int digit1; int digit2; digit1 = atoi(str[0]); digit2 = atoi(str[1]); // code continues and returns a string } 

argument of type "char" is incompatible with parameter of type "const char *" What does this mean ^^?

2
  • Does this resource help? It deals with a similar issue. stackoverflow.com/questions/55751920/… Commented May 29, 2021 at 1:44
  • 1
    atoi accepts "const char * ", when you do atoi(str[0]) it passess "char", that's why you are getting this error Commented May 29, 2021 at 1:46

2 Answers 2

3

atoi() takes a null-terminated string of characters, but you are trying to pass it a single character instead. You could do this instead:

char arr[] = {str[0], '\0'}; digit1 = atoi(arr); arr[0] = str[1]; digit2 = atoi(arr); ... 

But an easier way to convert a char in the range '0'..'9' to an integer of equivalent value is to subtract '0' from the character, thus:

'0' - '0' = 48 - 48 = 0 '1' - '0' = 49 - 48 = 1 '2' - '0' = 50 - 48 = 2 And so on... 
digit1 = str[0] - '0'; digit2 = str[1] - '0'; 
Sign up to request clarification or add additional context in comments.

2 Comments

The easiest way is probably atoi(str.c_str())
@MooingDuck That would convert the entire string, which is not what the OP wants
-1

If you want to convert each digit separately, you write something like below

//Instead of this: digit1 = atoi(str[0]); digit2 = atoi(str[1]); //use this: digit1 = (int)str[0] - '0'; digit2 = (int)str[1] - '0'; 

PS: you might need add validation for passed string is numeric.

8 Comments

why are you doing the -48?
On most but not all computers, 0 is 48.
@Bellfrank 48 is the ASCII code for '0'. Better to use '0' instead of a magic number.
@Bellfrank ASCCII value for 0 is 48, you can refer asciitable.com for ascci value of different characters
@Bellfrank read my answer, I show why '0' is subtracted
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.