我想將字符串轉換爲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;
}
請問'INT str_to_int(inputbase)'編譯您機?你使用什麼編譯器? – chux
這看起來非常像我的作業問題。 – ndim
我正在使用gcc編譯器。函數int str_to_int(inputbase)不會編譯 – vibeon7