.txt to ASCII Code Array

May 5, 2010 at 1:29am
How would I go about importing a text in to an array in ASCII code. Not the actual characters, but the number representation.

e.g. the .txt contains
"sample text"

I want it to load

115 97 109 112 108 101 32 116 101 120 116

in to a 2D array.

I dont really know how to approach this other than writing a separate program outside of what I want to do that loads each individual character and "manually" change it to a number.

Thanks
May 5, 2010 at 1:59am
Er, that's exactly what happens when you load strings from a file normally.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
  {
  const char s[] = "Hello world!";

  for (unsigned n = 0; n < sizeof( s ) - 1; n++)
    cout << (int)s[ n ] << " ";
  cout << endl;

  return 0;
  }
72 101 108 108 111 32 119 111 114 108 100 33 

If you want to copy a char array to an int array, use the copy() algorithm:
1
2
3
4
5
6
#include <algorithm>
...
const char s[] = "Hello world!";
int xs[ sizeof( s ) - 1 ];

std::copy( s, s + sizeof( s ) - 1, xs );

Etc. Hope this helps.
May 6, 2010 at 12:29am
Thanks, that worked beautifully.

Another possibly noobish question. How would I convert an ASCII number taken from an array to its corresponding letter\symbol?

EDIT:

Figured it out (I think)
Last edited on May 6, 2010 at 12:52am
May 6, 2010 at 1:16am
You've got it.

The only difference between and ASCII value and what gets printed is whether or not you are looking at it as a char or an int.

1
2
cout << (int)65 << endl;
cout << (char)65 << endl;

Enjoy!
Topic archived. No new replies allowed.