String To group of characters

Mar 4, 2012 at 4:29am
Hello, I have to write a program in which a string is converted into a group of characters which are then assigned an integer. So if the user enters the string "Hello World", the program would do: H = 1; e = 2; l = 3; o = 4; space = 5; W = 6; r = 7; d = 8.
Thank You
Mar 4, 2012 at 5:26am
AFAIK, this can't be done. What you are trying to do would involve assigning a value (a number) to something which is also a literal value (a character).
Unfortunately for you, variable names are a completely different thing to a char value, and when you compile your program, the variable identifiers are lost.
As for a solution to your problem, you would need some sort of container (such as a std::pair) to hold both a char and an integer, and then some way to iterate through them (such as an array and looping).
Mar 5, 2012 at 5:37am
This is one way using two arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    char a[]="Hello World";
    cout<<"\n";
    int b[]={1,2,3,4,5,6,7,8};
    for(int i=0;i<3;i++)
    cout<<a[i]<<" = "<<b[i]<<",";
    for(int i=4;i<7;i++)
    {cout<<a[i]<<" = "<<b[i-1]<<",";}
    cout<<a[8]<<" = "<<b[6]<<",";
    cout<<a[10]<<" = "<<b[7]<<". ";
    return 0;
}

/*prints
H = 1,e = 2,l = 3,o = 4, = 5,W = 6,r = 7,d = 8.
Process returned 0 (0x0) execution time : 0.063 s
Press any key to continue.
*/
Mar 6, 2012 at 1:21am
on second thoughts there is no need for a second array. something like this works as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
    char a[]="Hello World";
    cout<<"\n";
    int elem = 1;//used to count letters once
    for(int i=0;i<11;i++)
    {   if(i==3||i==7||i==9)continue;//jump the duplicates
        if(i==5)cout<<"space = "<<elem<<",";
        if (i==10)cout<<a[i]<<" = "<<elem<<".";//end with a period
        else if(i!=5)cout<<a[i]<<" = "<<elem<<",";//a[5] has already been dealt with

        elem++;
    }
    return 0;
}
/*prints
H = 1,e = 2,l = 3,o = 4,space = 5,W = 6,r = 7,d = 8.
Process returned 0 (0x0)   execution time : 0.109 s
Press any key to continue.
*/
Topic archived. No new replies allowed.