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";
题
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.
解决方案
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";
其他提示
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)
.
You forgot quotes in the strings:
char year[4] = "2014";
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";