[英]How to convert char string to one single int number if the string also contains letters
我有一個非常基本的問題,如果我有一個像這樣的char charv1[6] = "v445"
字符串: char charv1[6] = "v445"
或v666
如何獲取數字並將它們轉換為值為445
或666
的單個整數?
我一直在嘗試這段代碼,但是出了點問題...:
size = (strlen(charv1)-1);
for(aux = size; aux > 0; aux--){
if(aux == (size)){
v1 = charv1[aux]-'0';
}
else{
aux2 = (charv1[aux]-'0')*10;
printf("%d\n", aux2);
v1 = v1 + aux2;
}
}
charv1
包含字符串: v445
等
我記得幾年前,我是遞歸地做的,但是我不記得是怎么做的,但是現在我不需要一個優雅的解決方案了……我需要一個可行的解決方案。
只需使用strtol
,
long int num;
char* end;
num = strtol(&charv1[1], &end, 10);
有一個名為strtol()
的函數,它的用法如下:
long dest = 0;
char source[10] = "122";
dest = strtol(source , NULL , 10); // arg 1 : the string to be converted arg2 : allways NULL arg3 : the base (16 for hex , 10 for decimal , 2 for binary ...)
但是在您的情況下,您應該替換此dest = strtol(source , NULL , 10);
使用此dest = strtol((source + 1) , NULL , 10)
或dest = strtol(&source[1] , NULL , 10);
忽略第一個字符,因為strtol
在遇到的第一個非數字字符處停止
sscanf怎么樣
sscanf( charv1, "%*c%d", &i); //skip the first char then read an integer
然后
int x = atoi(&charv1[1]);
printf("Here it is as an integer %d\n", x);
您忘記了每個循環要乘以10。 這有效:
size = (strlen(charv1)-1);
dec=10;
for(aux = size; aux > 0; aux--){
if(aux == (size)){
v1 = charv1[aux]-'0';
}
else{
aux2 = (charv1[aux]-'0')*dec;
printf("%d\n", aux2);
v1 = v1 + aux2;
dec*=10;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.