转换而不使用预定义的方法

时间:2015-10-24 12:23:29

标签: c

我正在实现一个函数接受数组并返回它的值,代码似乎都很好,除了转换部分。

#include <stdio.h>

int length=10;

int function (char s){ 
int n=0,i;
for ( i = 0; i < length; i++)
     {  
printf(" %d = %x   %c \n ", i, s, );
n = n * 10 + ;  
 s++;
     }

return n;
}

int main(){
char p[10];
printf("enter string ");
scanf("%s",p);
printf("\n");

int number;
number =function(p);
printf("  %d \n",&number);
return 0;}

3 个答案:

答案 0 :(得分:1)

char *p[10];应为char p[10];。你想要一个字符数组,而不是一个指向字符的指针数组。

printf(" returned value %d \n",&number);应为printf(" returned value %d \n", number);,因为您要打印号码,而不是号码的地址。

通过这2项更改,它可以正常运行:http://ideone.com/HMjoRZ

答案 1 :(得分:0)

printf(" returned value %d \n", number);
                                ^^^^^^

否则使用&number您尝试将number的地址输出为整数值。

至于函数本身,可以用以下简化的方式编写

#include <stdio.h>
#include <ctype.h>

int convert( const char *s )
{ 
    int numericValue = 0;
    enum { POSITIVE, NEGATIVE } sign = POSITIVE; 

    while ( isspace( ( unsigned char )*s ) ) ++s;

    if ( *s == '-' ) sign = NEGATIVE;
    if ( *s == '-' || *s == '+' ) ++s;

    for ( ; isdigit( ( unsigned char )*s ); ++s ) numericValue = 10 * numericValue + *s - '0';

    if ( sign == NEGATIVE ) numericValue = -numericValue;

    return numericValue;
}

int main( void )
{
    printf( "%d\n", convert( "-12345" ) );
    printf( "%d\n", convert( "+12345" ) );
    printf( "%d\n", convert( "12345" ) );
    printf( "%d\n", convert( "12A345" ) );

    return 0;
}

它的输出是

-12345
12345
12345
12

答案 2 :(得分:0)

发布的代码存在许多问题,修复如下。这会干净地编译并执行所需的功能并正确处理非数字输入并执行适当的错误检查

警告:只处理正数

#include <stdio.h>
#include <ctype.h> // < for the 'isdigit()' function

// Use #define rather than a variable
#define LENGTH          10

// use this #define pattern for variable max length in scanf()
#define str(x)          # x
#define xstr(x)         str(x)

int function (char *s) // passed in parameter is a pointer to string
{
    int n=0;
    int i;

    for ( i = 0; s[i]; i++) // terminate loop when NUL byte encountered
    {
        if( isdigit( s[i] ) ) // < note check for valid input
        {
            //printf(" %d = %x   %c \n ", i, s, );
            n = (n * 10) + (s[i]-'0') ;
        }
        else
        { // then char not in range '0'...'9'
            break;
        }
    }

    return n;
}

int main( void )
{
    char p[ LENGTH+1 ]; // < note correction +1 because scanf adds NUL byte

    printf("enter string ");
    if( 1 != scanf("%"xstr(LENGTH)"s",p) )
    { // then scanf failed
         perror( "scanf failed for input string" );
         exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("%s\n", p);

    int number;
    number =function(p);
    printf("  %d \n",number);  // < note correction
    return 0;
}