How to convert string array to ascii

Hello how to convert 2d string array to ascii?
This is my array
string n[5][5] = { { "1", "2", "3", "4","5" }
,{ "6", "7", "8", "9","10" }
,{ "11", "12", "13", "14","15" }
,{ "16", "17", "18", "19","20" }
,{ "21", "22", "23", "24","25" } };
I would do this:
1
2
3
4
5
for (int i = 0; i < 5; ++i)
    for (int j = 0; j < 5; ++j)
    {
        int some_ascii_value = (int)(n[i][j][0]);
    }
it is in ascii, unless you are in unicode or something via compiler settings (?).
@jonnin I want to convert every element in the string array to their ascii value using func
there is nothing to do.

strings are chars. Chars are ascii. Chars are integers.
if you simply print the value as an int instead, it is done, there is no function to call.

cout << (int)(n[x][y][0]); //the first letter of the string at x,y position in the 2d array as the ascii value in base 10. You may prefer hex, in which case you can print it in hex.

you can loop over that for all x, for all y, for 0..size() of the string (instead of zeroth location) if you want.

I'm pretty sure guessing that OP means convert the string "23" into the character 23, i.e "end of transmission block". I don't know why OP is trying to do it in this convoluted manner, but I would use stringstream conversions. Apparently std::sprintf could also be used, but I have not tried that. http://www.cplusplus.com/forum/beginner/226206/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <sstream>
#include <iostream>
int main()
{
    std::string n[5][5] = {
             {  "1",  "2",  "3",  "4",  "5" },
             {  "6",  "7",  "8",  "9", "10" },
             { "11", "12", "13", "14", "15" },
             { "16", "17", "18", "19", "20" },
             { "21", "22", "23", "24", "25" }
    };
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            const std::string& s = n[i][j];
            std::istringstream iss(s);
    
            int value;
            char c;
            if (iss >> value) // conversion successful.
            {
                c = static_cast<char>(value);
                std::cout << "ascii value " << value << " = " << c << std::endl;
            }
            else
            {
               std::cout << "failed to convert " << s << std::endl; // handle conversion error.
            }

        }
    }

}
Last edited on
Topic archived. No new replies allowed.