我在将带符号的字符串转换为int时遇到问题。
char *crn1, *crn2, *credit1, credit2;
char course1, course2;
crn1=strtok(course1,"/");
credit1=strtok(NULL,"/");
crn2 = strtok(course2,"/");
credit2 = strtok(NULL,"/");
我正在尝试将带符号的字符credit1或credit2转换为整数,以便稍后在代码中使用。我要么得到一个巨大的数字,要么得到一个错误。
发布于 2018-08-29 06:44:30
#include <stdlib.h>
#include <stdio.h>
int main() {
char *str = "5";
int n;
n = strtol(str, NULL, 10);
printf("n+1 is %d\n", n+1);
}
使用atoi
#include <stdlib.h>
#include <stdio.h>
int main() {
char *str = "1";
int n;
n = atoi(str);
printf("n+1 is %d\n", n+1);
}
如果不是将字符串中的数字转换为整数,而是使用字符的数值,则可以:
#include <stdio.h>
int main() {
char c = 'a';
printf("ascii code of %c is %hhu\n", c, c);
printf("after %c is %c with ascii code %u", c, c+1, c+1);
return 0;
}
https://stackoverflow.com/questions/52066414
复制相似问题