2014-09-10 84 views
-1

如何将字符串转换为整数而不使用atoi参数?以下是我所尝试的:将字符串转换为整数而不使用atoi

int main(int argc, char *argv[]){ 
    for(int i = 1; i < argc; i++){ 
     const char *p = argv[i]; 
     int j = 0; 
     while(isdigit(*p)){ 
      j = j * 10 + *p - '0'; 
      p++; 
      printf("%d\n", j); 
     } 
    } 
} 

由于某些原因,它会分裂并重新添加它们。

$ ./a.out 55 6 50 66 
5 
55 
6 
5 
50 
6 
66 
+3

'的printf( “%d \ n” 个,J);'移动到后while循环。 – BLUEPIXY 2014-09-10 23:31:37

回答

0

您正在打印所有中间结果。保存打印输出,直到完成while循环。

while(isdigit(*p)){ 
    j = j * 10 + *p - '0'; 
    p++; 
} 

printf("%d\n", j); 
-1
#include<iostream> 
#include<string> 

using namespace std; 
int main() 
{ 
    //char name[1000]; 
    //cin>>name; 
    char name[]="123456"; 

    int data, result, output,Base; 
    //volatile int Base; 
    //int Base; 
    data=1; result=0; Base=strlen(name); 
    while (Base>= 1) 
    { 
     Base--; 
     output=toascii(name[Base])-48; 
     output=output*data; 
     result= result+output; 
     data=data*10; 
    } 
    std::cout<<"this is the string you enterd"<<name<<"integer is"<<result; 

    return 0; 
}