Reputation: 13
I have parsed some date and time from GPS receiver. And need to convert them from string to int
:
char year[4] = "2014";
char month[2] = "01";
char day[2] = "24";
char hour[2] ="12";
char minute[2] = "58";
char second[2] = "39";
GPS_current_year = atoi(year);
GPS_current_month = atoi(month);
GPS_current_day = atoi(day);
GPS_current_hour = atoi(hour);
GPS_current_minute = atoi(minute);
GPS_current_second = atoi(second);
After executing these the results are:
Somehow part of minutes string is converted when converting hour string. Same with minutes and seconds.
The strings are placed side by side in the memory.
If I change the sequence of defining strings then seconds may be added to years etc.
Questions:
atoi
?I know that I can convert using a loop one char
at a time. Just trying to find why is it not working.
Upvotes: 1
Views: 7073
Reputation: 4002
atoi()
converts string to integer. But you are giving non string values to your string variables. Change your code to
char year[5] = "2014";
char month[3] = "01";
char day[3] = "24";
char hour[3] ="12";
char minute[3] = "58";
char second[3] = "39";
Upvotes: 0
Reputation: 154315
Suggest not trying to define the string size as 4 or 5.
Let the compiler determine the string size.
char year[] = "2014";
In this case, the compiler will make year
with a size of 5 initialized with '2'
, '0'
, '1'
, '4'
, '\0'
.
OP's defining the size as 4 resulted in a size of 4-char array without a terminating '\0'
, which not being a string, create problems with atoi(year)
.
Upvotes: 3
Reputation: 68972
Besides the missing quotes around the strings your char array's size should be defined to hold one more char the EOS (end of string a binary zero).
Since the memory representation would be e.g. "2014\0"
char year[4+1] = "2014";
Upvotes: 3