Convert string to ASCII?

Hi, how can I convert a string to ASCII code? I looked up examples in Google but they all use arrays and advance codes, I haven't learned arrays yet, can someone explain me how to convert it please?

I know I can't convert directly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string user;

	getline(cin, user);

	cout << static_cast<char>(user);






	return 0;
}
Last edited on
A string obtained via getline is a series of ASCII characters.

Line 11: You can't convert an entire string into a single character.

You can however reference individual characters of the string:
 
  cout << user[0];  // Assumes the string is not empty 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;


int main()
{
    string user;
    int ascChar;

    getline(cin, user);

    cout << user << endl;

    for (int i=0;i<user.length();i++)
    {
        ascChar = user[i];
        cout << ascChar << endl;
    }

    return 0;
}

Last edited on
AbstractionAnon when you say [0] what does the brackets mean?

CodeWriter that's the same code I found online, what does these mean?

1
2
3
user.length()

[i]

?
Last edited on
returns the number of characters in the string list user.
Strings are lists of ascii number codes in the computer.

length is a member function (that is why the . is used and the () are to indicate it is a function) of a string and when called returns the number of characters the string contains.
http://www.cplusplus.com/reference/string/string/length/

the square braces grab a character at a given position in the string, basically the first character is memory position 0 and then if you put in any other number it will get the character with an offset from the start eg the second character would be index 1 since it is an offset of 1 from the first character. Alternatively you can do it using pointer notation. The square braces are known as "operator []" and is another function of the string class.
http://www.cplusplus.com/reference/string/string/operator[]/
Topic archived. No new replies allowed.