Strange output

Hey all,

I'm trying to write a simple short code that takes a few input characters and finds each character's number in the alphabet. My goal is that it returns an array with these indices, so that for the fairly random input word: "pepper", it would return [15,4,15,15,4,17]. However, I get some strange things too. It sort of works, but not quite.
Here's the code:
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
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string.h>
#include <string>

using namespace std;

int main(){
  char modalpha[] = "abcdefghijklmnopqrstuvwxyz";
  char message[100];
  cin >> message;
  int length = strlen(modalpha);int i;int meslength = strlen(message);
  int j;int count=0;
  int indices[1000];
  for(i=0;i<meslength;i++)
    {
      for(j=0;j<length;j++)
	{
	  if(message[i]==modalpha[j])
	    {
	    indices[count]=j;
	    count=count+1;
	    cout<<j<<endl;
	    break;
	    }
	}
    }
  for(i=0;i<=4;i++)
    {
      cout<<indices<<endl;
    }
  return 0;
}


And when I run the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
peder@peder-ThinkPad-X220:~/C++$ g++ indexTest.cpp
peder@peder-ThinkPad-X220:~/C++$ ./a.out 
pepper
15
4
15
15
4
17
0x7fff733d8cd0
0x7fff733d8cd0
0x7fff733d8cd0
0x7fff733d8cd0
0x7fff733d8cd0
peder@peder-ThinkPad-X220:~/C++$ 


So, 15,4,15,15,4,17 are the ones I expected, but those last 5 lines I don't understand.
Thanks for any help!
Line 31 prints the address of indices, you want cout << indicies[i] << endl;

That "4" in line 29 should be "count - 1", right? (or perhaps i < count)

Edit: Btw, a char is printed as a letter, but it is actually an integer.

Try:
1
2
char letter = 'a';
cout << "The letter " << letter << " has a value of " << (int)letter << endl;


Refer to an ASCII table near you :)
Last edited on
What this code shall to display?!

1
2
3
4
for(i=0;i<=4;i++)
    {
      cout<<indices<<endl;
    }
@LowestOne: Thanks! That explains a few things indeed! But if I want it to return the entire array when this function is called elsewhere, would it work if I set the return to:
return indices;?

@vlad: That cout-loop was just to check if the first few integers were right -- as LowestOne pointed out, it would be more complete if it used count-1 rather than 4 (which was very arbitrary) :)
Topic archived. No new replies allowed.