converting char to ascii code

Hi to all,

here's what I'm faced with.

I know that one can do:

char c='b';
int i=c;

and that would give the ascii code of the letter b. So far so good.

Now, this is what I have. I define the function:

vector<string> my_vector(vector<string> my_vector2)
{


for(int i = 0; i < my_vector2.size(); i++)
{
int c = my_vector2[i];
//more stuff here

}

//more stuff here
}


What's wrong with the line in bold? How would I access the ascii code of a specific character in the vector?

Thanks!
chrisname thanks! Actually this is what I've been trying

int c = my_vector2.at(i);
Also

int c = (int)my_vector2.at(i);
Also
int c = (int)(my_vector2.at(i));

but none seems to work.

All I wanted is get the ascii code of my_vector2 at the ith position.


Well, what problem do you get when you use at or operator[]?

Edit: do you get a compile-time error or a runtime error? If so, what happens?
Last edited on
when I use

int c = (int)my_vector2.at(i);

I get a compile-time error

19 C:\Dev-Cpp\main.cpp `struct std::basic_string<char, std::char_traits<char>, std::allocator<char> >' used where a `int' was expected

You have a vector of STRINGS not a vector of chars.

If you want to pull a specific character out of a string out of the vector, you need to have double brackets:

1
2
3
4
5
6
// example:
string foo = my_vector[ whatever_string_you_want ];
int c = (int)foo[ whatever_character_you_want ];

// or... without the temp var:
int c = (int)my_vector[ whatever_string_you_want ][ whatever_character_you_want ];
Oh, so he does :P
I should learn to read.
cool. And so say that I am using a vector of characters how do I pass a vector to the function?

After the function has been defined can I simply say

int main(int argc, char* argv[])
{
cout << my_vector ('Hello World')<< endl;
return 0;
}

Is this is how I pass a vector of characters into the function? Put that vector of characters (in the case the sentence Hello World) into quotes?

Because when I tried to call the function this way at compilation I got

54:29 C:\Dev-Cpp\main.cpp [Warning] character constant too long for its type

and

54 C:\Dev-Cpp\main.cpp conversion from `int' to non-scalar type `std::vector<char, std::allocator<char> >' requested
And so say that I am using a vector of characters how do I pass a vector to the function?


It would be just like vector<string>, only instead of typing vector<string>, you type vector<char> =P

Also you give it characters instead of strings. But the vectors are passed to/from functions the same way.

my_vector ('Hello World')


'Hello World' is not a vector, so no, that would not work.

You also can't output a vector to cout.

This is making less and less sense. What exactly are you trying to do?
Topic archived. No new replies allowed.