[please help] converting text to ascii

Jun 6, 2016 at 10:55am
I have to write console program where it changes any text to ASCII. The text has to be written to array and then converted.
For example:
input: Nc
output: 7899

I only have this, but it's converting only first char and after putting Nc there's only 78. Please help.

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
  int main()
{
	unsigned char text;
	int array[256];
	int i = 0;
	int ascii;

	cout << "Write text:" << endl;
	cin >> text;


	for (int i = 0; i < 256; i++)
	{
		array[i] = text % 256;
		text = text / 256;
	}


	for (i = 0; i < 256; i++)
	{
		ascii = (int)array[i];
	}
	
	cout << "ASCII: \n" << ascii;


	system("pause");
    return 0;
}
Jun 6, 2016 at 11:14am
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string.h>

int main()
{
    char text[100];

    std::cout << "Write text: ";
    std::cin >> text;

    for (int i = 0; i < strlen(text); i++)
       std::cout << (int)text[i];
	
    return 0;
}


Write text: Nc
7899 
Last edited on Jun 6, 2016 at 11:15am
Jun 6, 2016 at 11:26am
Thank you so much! Can you tell me why there has to be 100 and not 256? And what "strlen" does?
Jun 6, 2016 at 11:33am
closed account (48T7M4Gy)
Try it out with different sizes. Try 256. If you look up 'arrays' in the tutorial you'll see how they work and why 100 would cover most sentence inputs. Try 2 and there won't be enough storage space for sentences of more than 2+1 characters and the program will crash.

strlen() is a function that is included in string.h and it determines the number of characters in the sentence. Have a look in the reference section of this site http://www.cplusplus.com/reference/cstring/strlen/?kw=strlen

You're on the right track if you study/understand/learn about each line of the code I wrote and compare/adapt it with yours. The temptation is to just copy it and not learn anything.
Last edited on Jun 6, 2016 at 11:57am
Topic archived. No new replies allowed.