0

I had created a question to understand the convertion of ascii characters to integer. Here is the question which i created: How to do math operations in Ascii? .I solved my problem according to those answers. But i am having difficulty in completing it to my requierement. I have a char array which containts the latitude value like this:

char *latitude = "4055.1792,N";

I need to get the number between 3rd digit and comma, divide it by 60 and add it to first 2 digit. So for this example, the new latitude value must be:

4055.1792 corresponds to 40 +(55,1782)/60 = 40.9196

Then convert it to char string again, like this:

*latitude = "40.9196,N";

I converted the value to integer and made math operations but the code is getting so long and messy if i convert it to string again. Is there a way to do it simply? Here is what i have done till now,

int tmpLat[8];
int temp = 0;
char *latitude = "4055.1792,N";

tmpLat[0] = latitude[0] - '0';
tmpLat[1] = latitude[1] - '0';
tmpLat[2] = latitude[2] - '0';
tmpLat[3] = latitude[3] - '0';
tmpLat[4] = latitude[5] - '0';
tmpLat[5] = latitude[6] - '0';
tmpLat[6] = latitude[7] - '0';
tmpLat[7] = latitude[8] - '0';

temp = tmpLat[2]*100000 + tmpLat[3]*10000 + tmpLat[4]*1000 + tmpLat[5]*100 + 
            tmpLat[6]*10 + tmpLat[7];

temp = temp/60;

printf("\r\nResult = %d%d.%d,%c\r\n",tmpLat[0],tmpLat[1],temp,latitude[10]);

I can cast them to string now but i think i'm doing somethings with long ways.

Community
  • 1
  • 1
abdullah cinar
  • 543
  • 1
  • 6
  • 20

1 Answers1

1

This should scan two digits into an integer and then a double.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main( ) 
{
    char *latitude = "4055.1792,N";
    char dir = '\0';
    int deg = 0;
    double min = 0.0;
    double conv = 0.0;

    if ( sscanf ( latitude, "%2d%lf, %c", &deg, &min, &dir) == 3) {
        conv = deg + ( min / 60.0);
        printf ( "%f, %c\n", conv, dir);
    }
    return 0;
}
user3121023
  • 8,181
  • 5
  • 18
  • 16