views:

926

answers:

2

code below. i'm tryind to obtain string answers like "a1", "c4"

this is what i'm having instead of "a1": "adresse finale: \340}00\214" with this prinf:

    printf("\nadresse finale: %s",[self convertCGPointToSquareAdress:self.frame.origin]);

the method is:

-(NSString *) convertCGPointToSquareAdress:(CGPoint ) point{
int x= point.x /PIECE_WIDTH;
int y=point.y/PIECE_WIDTH;
char lettreChiffre[2];
//char chiffre;
NSString *squareAdress;
//ascii a=97 , b=98... h=105
for (int i=97; i<105; i++) {
 for (int j=8; j>0; j--) {
  if(i-97==x && j-1==y ){
   NSLog(@"enterrrrrrrrrred if convertCGPointToSquareAdress"); 
   lettreChiffre[0]=i;
   lettreChiffre[1]=(char) j;
   printf(" lettreChiffre: %s ", lettreChiffre);
   NSString *squareAdress=[NSString stringWithFormat:@"%s", lettreChiffre];
   break;
  }
 }
}
return squareAdress;

}

can you please help me? thanks in advance.

+2  A: 

There are three problems I can see with your code:

1. When you do

lettreChiffre[1]=(char) j;

remember j is a number between 1 and 8, so you're getting the ASCII character whose value is j, not the character 1...8. You should use

lettreChiffre[1]= '0' + j;

2. lettreChiffre is a char array of length 2, which means there's no room for the terminal null character. This may work, but may give you gibberish. You should instead declare

char lettreChiffre[3];
lettreChiffre[2] = '\0';

3. You're trying to use printf to print an NSString, which it can't do. Either use

NSLog(@"adresse finale: %@", mynsstring)

or convert the NSString back to a C-string:

printf("adresse finale: %s", [mynsstring UTF8String]);

Also, as noted by @dreamlax, you don't really need the loop. I assumed you were doing something else and ran into this trouble, so we're not really seeing the full code. But, if this is really the entirety of your code, then you can simply remove the loop as @dreamlax suggested.

Jesse Beder
it works. thanks
kossibox
+2  A: 
dreamlax
thank your for answering
kossibox