How can I efficiently convert char to int?

You have a string of digits from 1-8.Now you need to increase each digit by 1 and put back in the same index of the string. But you can’t use additional containers. How can you do it?

Input: 12345678
Output:23456789

My typecasting process seems not to working .

    string s;cin>>s;
	int n=s.size();
	for(int i=0;i<n;++i){
		s[i]=(char)(s[i]-'0'+1);
	}
	cout<<s;

s[i]='0' + (char)(s[i]-'0'+1);

Edit:

Or s[i]++.

2 Likes

for(int i=0;i<n;i++)
{
int num = s[i] - β€˜0’;
num++;
char c = num + β€˜0’;
s[i] = c;
}

1 Like

Thank you so much

1 Like

@ssjgz bro (char)(s[i]-β€˜0’+1); this part is not giving any value why?
s=β€œ234”;
for i=0
value will be (char)(2-48+1) which is negative but it should print something ?

value will be (char)(50-48+1) not (char)(2-48+1) here 2 is a char so (β€˜2’ - β€˜0’ + 1).
And for the problem you can just jo s[i]++.

but still (char)(2-48+1) this part does not print anything u can try until u add β€˜0’ at begging
is it becuz whole value is character

yes it will print something surely which will be a char.
but (char)(1) is not a number. You can refer to ASCII table for char of every integer value.

adding β€˜0’ in (char)(50-48+1) will run something like this.
β€˜0’ = char(48)
so char(48) + char(3) = char(51) which gives us β€˜3’.

You can see it this way.

sorry for mistake but if U try to print only this (char)(50-48+1) which is char(3) (in a loop to get all value increment but not adding 0 ) so i am not getting out see->

int main()

{

string s="234";

for(int i=0; i<s.length(); i++)

{

s[i]=(char)(s[i]-'0'+1);

//cout<<s[i];

}

cout<<s<<nl;

}
 output for this is nothing.

why ?

char(3) is End of Text so that is why you get no output.

bro can u explain about little bit wht is End of Text how it work in string

You should see the ASCII table first then you will get the idea.

EOT is similar to NewLine char(10).

When you send some data like a text then, when the receiving device sees EOT it will stop receiving data or it will see NEWLINE it will do accordingly. Similarly, there are some other char you can see in the ASCII table.

It has nothing to do with the string.

When you start cout it will start collecting data and will print. But you introduced EOT at the start means there is nothing to print.
Also, EOT will take 3 spaces, So if you print a length 5 string starting with EOT, it should print the last 2 characters of the string.

Hope you get it.

1 Like

learned something new

1 Like