C++中把char[]转成int,怎么转?

2024-11-22 05:30:30
推荐回答(5个)
回答1:

无论字符串长度,只读最后4位,用 sscanf.
c++ 多2行头文件:
#include
using namespace std;
#include
main(){
char s[]="x_y_z4321";
int v;
int L;
L=strlen(s);
sscanf(s+L-4,"%d",&v);
printf("v=%d\n",v);
}

回答2:

//#include "stdafx.h"//vc++6.0加上这一行.
#include 
using namespace std;
int main(void){
    char a[]="jfjkdsla;jg;kdsla8890",b[50];
    int n;
    sscanf(a,"%[^0-9]%d",b,&n);
    cout << n << endl;
    return 0;
}

回答3:

char s[]="abc1234";
char *p = s;
p += 3;
int i = atoi(p);

回答4:

#include
using namespace std;
int char2int(char c[])
{
int res = 0;
int count = 0;
for (; c[count] != '\0'; count++) { }
for (int i = 1; count > 0; count--)
{

res += (c[count-1] - 48)*i;
i *= 10;
}
return res;
}
void main()
{
char c[] = "123";
int i = char2int(c);
cout << i;
}

回答5:

sscanf( &chr[ strlen(chr) - 4 ],"%d",&n );