H.Ghassami
H.Ghassami

Reputation: 1022

Converting char to ascii value

I know it is stupid question but it does not resolve, and I am googling but that didn't help either. I want to select the sub string from my string and then convert it to ASCII value, but it shows me an error:

int a=char(S.substr(i-1,1));
        int b=S.substr(i ,1);
      if (( a== 13) && (b== 10))
        break;  

this is my error :

pdusms.cpp:1020: error: invalid cast from type 'std::basic_string' to type 'char' int a=char(S.substr(i-1,1));
pdusms.cpp:1021: error: invalid conversion from 'const char*' to 'int' [-fpermissive] int b=S.substr(i ,1).c_str(); ^
How can i do that? how can i change the char to int (show ASCII value)

Upvotes: 0

Views: 1201

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

The result of substr is a string, not a character.
A one-character string is not a character.

Use indexing to get the characters.

You want

int a = S[i-1];
int b = S[i];

but if you're looking for line delimiters you shouldn't compare to ASCII values - use

if (S[i-1] == '\r' && S[i] == '\n')

which is portable.

Upvotes: 2

Related Questions