May 26, 2021 at 2:48pm UTC
a is a string. I want to store the ascii values of each character of the string in a vector and also print them out. How do I do that?
vector<string> vektor; // vektor
vektor.push_back(a);
for (int i=0;i<a.length();i++)
{
ascChar = a[i];
cout << ascChar << " ";
}
May 26, 2021 at 2:52pm UTC
what is a?
anyway..
1 2 3 4 5 6 7 8 9
string s{"hello world" };
vector<char > c(s.length());
for (int i = 0; i < s.length(); i++)
c[i] = s[i];
cout << s; //lazy way to print.
for (auto a:c)
cout << a; //verification print.
you can probably use standard copy or something instead of a for loop if you prefer.
Last edited on May 26, 2021 at 2:53pm UTC
May 26, 2021 at 4:21pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <string>
#include <vector>
#include <iostream>
int main() {
const std::string a {"hello world" };
const std::vector<unsigned > c(a.begin(), a.end());
std::cout << a << '\n' ;
for (const auto a : c)
std::cout << a << ' ' ;
std::cout << '\n' ;
}
hello world
104 101 108 108 111 32 119 111 114 108 100
Note that if you store as vector<char> then the char itself will be displayed - and not the ASCII value.
Last edited on May 26, 2021 at 4:48pm UTC
May 26, 2021 at 8:21pm UTC
oh, if you want the int value, you can also get that from the string without re-storing it in a new container.
(int)s[index] is the ascii integer value, you can print it with a cast, without re-saving it. Do you need to store a copy as something else, knowing that?