Getting object c nsstring from c char []

below. I'm trying to get string responses like "a1", "c4"

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

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

method:

-(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;

}

Could you help me? thanks in advance.

+3
source share
2 answers

There are three problems that I see with your code:

1. When do you

lettreChiffre[1]=(char) j;

remember jis the number between 1and 8, so you get an ASCII character whose value j, not a character 1...8. You have to use

lettreChiffre[1]= '0' + j;

2. lettreChiffre char 2, , . , .

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

3. printf NSString, .

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

NSString C-:

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

, @dreamlax, . , - , . , , , @dreamlax.

+2

? , " ". , x 8.

.

- (NSString *) convertCGPointToSquareAdress:(CGRect) point
{
    unsigned int x = point.x / PIECE_WIDTH;
    unsigned int y = point.y / PIECE_WIDTH;

    // Do some range checking to ensure x and y are valid.

    char lettreChiffre[3];
    lettreChiffre[0] = 'a' + x;
    lettreChiffre[1] = '1' + y;
    lettreChiffre[2] = '\0';

    return [NSString stringWithCString:letterChiffre encoding:NSASCIIStringEncoding];
}
+2

Source: https://habr.com/ru/post/1717917/


All Articles