C程序调用字符串为int函数,我无法转换输入

问题描述:

我想将字符串转换为int并从main调用该函数。第一个字符是一个声明数字基数的字母,而字符串中的其余字符是数字。我能够使该功能单独工作,但使用main函数调用它时将不会输出正确的值。使用二进制用户输入的C程序调用字符串为int函数,我无法转换输入

例子:

b1000 
b1010 

的结果应该是:

b 
b 
1000 
1010 

下面是代码:

#include <stdio.h> 
#include <string.h> 
#include <math.h> 

int str_to_int(inputbase) { 
    char num1[50]; 
    num1[50] = inputbase; 

    char numcpy1[sizeof(num1) - 1]; 

    int i, len1; 
    int result1 = 0; 

    //printf("String: "); 
    //gets(num1); 

    //Access first character for base 
    printf("%c \n", num1[0]); 

    //Remove first character for number1 and number 2 
    if (strlen(num1) > 0) { 
     strcpy(numcpy1, &(num1[1])); 
    } else { 
     strcpy(numcpy1, num1); 
    } 
    len1 = strlen(numcpy1); 

    //Turn remaining string characters into an int 
    for (i = 0; i < len1; i++) { 
     result1 = result1 * 10 + (numcpy1[i] - '0'); 
    } 

    printf("%d \n", result1); 
    return result1; 
} 

int main() { 
    char *number1[50], *number2[50]; 
    int one, two; 

    printf("\nAsk numbers: \n"); 

    gets(number1); 
    gets(number2); 

    one = str_to_int(number1); 
    two = str_to_int(number2); 

    printf("\nVerifying...\n"); 
    printf("%d\n", one); 
    printf("%d\n", two); 

    return 0; 
} 
+1

请问'INT str_to_int(inputbase)'编译您机?你使用什么编译器? – chux

+0

这看起来非常像我的作业问题。 – ndim

+0

我正在使用gcc编译器。函数int str_to_int(inputbase)不会编译 – vibeon7

我想你的代码不能因为一些编译错误。

第一个是在inputbase而没有类型定义的线

int str_to_int(inputbase) 

如果改为

int str_to_int(char * inputbase) 

下一个点改进是符合

num1[50] = inputbase; 

一样,没有设置错误的assignement:

  1. num1[50]意味着获得第51届项目,但从0到49索引的只有50个项目
  2. 声明num1[0] = inputbase;(以及任何其他正确的指数)是错误的,因为在类型区别:num1[0]char,但inputbase是指针
  3. num1 = inputbase;也将是错误的(字符串=不能在C中使用的复制,所以考虑使循环或使用标准库函数strncpy

而且,由于这只是问题的开始,我建议从十进制输入使用一些标准功能转换char*字符串int开始(如atoi,或sscanf),再经过你检查程序,并找到它,如果它正确的,需要你能避免使用标准转换,写自己的str_to_int

+0

不主张使用'strncpy()',它永远不是正确的工具,特别是对于初学者。也不鼓励使用'gets()'。 – chqrlie

原型为你的函数str_to_int()应指定intputbase类型。您正在传递一个字符串,并且str_to_int没有理由修改此字符串,因此该类型应为const char *inputbase

此外,你不需要为字符串的本地副本,只需访问的第一个字符相应地确定基和解析其余数字:

#include <stdlib.h> 

int str_to_int(const char *inputbase) { 
    const char *p = inputbase; 
    int base = 10; // default to decimal 

    if (*p == 'b') { // binary 
     p++; 
     base = 2; 
    } else 
    if (*p == 'o') { // octal 
     p++; 
     base = 8; 
    } else 
    if (*p == 'h') { // hexadecimal 
     p++; 
     base = 16; 
    } 
    return strtol(p, NULL, base); 
}