Hey, I have a small problem. I need to convert a char into an int, except the char has 2 values inside it.

For example

``````char c = 'v0';
int i = c - '0';

cout << i << "\n";``````

All that does is removes '0' from the first value which is v, how would I go about ignoring or jumping over the 'v' value straight into the 0 so that i can convert it into an int?

cheers

There is no char as 'v0'
char constitute only one character.
Multi-character constants are undefined by the language.
So don't use them.
While converting to int, only last character is read. That means: `int i=(int)'ac' ;//will store the ascii value of c`

hmm thats strange because when i run my code above the cout shows the i value as 70 :S

Now I tried using your version and the value of i is 118 (ascii value of v).

To further clarify, I need to enter a char variable and then convert the char into an int.

so

``````char c;
int i;

cin >> c;
i = c - '0'
cout << i ;``````

>>hmm thats strange because when i run my code above the cout shows the i value as 70
Yeah, that is strange because it is undefined. It is not defined by the language and so is implementation dependent.

>>To further clarify, I need to enter a char variable and then convert the char into an int. `i = c - '0'` is not correct way. What if the value user enter A? Its ASCII value is 65 so 65-48=17 but this is not what you want right?
So you should do `i=static_cast<int>(c) ;` which would print the actuall ascii value : 65

PS : Throughout the discussion I am assuming that 'converting' char to int means determining its ascii value. If you meant to convert a character '1' to int 1 then go with the minus '0' aproch

the static_cast still gives the ascii value of 118, is there any way of making the v0 char equal to int 0? (and subsequently v1 char = int 1)

the static_cast still gives the ascii value of 118, is there any way of making the v0 char equal to int 0? (and subsequently v1 char = int 1)

Yes there is : just substract 'v0' instead of stubstracting '0'

``````#include<iostream>
int main()
{
const char k='v0';//the constant char need to be stubstracted
char c='v7';//chage this to whatever value you want
int i=c-k;

std::cout<<i;
}``````

Will print 7

PS:
I don't know why are you after multi-character chars. You should perhaps use cstring(i.e. char ) to store the value and then call strcmp() from cstring header file to compare with "v0"

``````//much neater code
#include<iostream>
#include<cstring>
int main()
{
const char a="v7";
std::cout<<strcmp(a,"v0");
}``````

thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.