2014-09-30 40 views
-1

我在讀取argv [3]作爲字符串時遇到問題,但隨後將其作爲整數轉換爲整數。我讀strtol可以做到這一點,但sscanf應該足夠?究其原因,如果STRCMP(的argv [],聲明的是,我將增加基部16和8版本。非常感謝你。從命令行讀取並使用sscanf轉換爲整數

#include <stdio.h> 
#include <math.h> 
int binary_decimal(char *); 
int main(int argc, char **argv) 
/* Declare data types*/ 
{ 
if (strcmp(argv[1], "dec")) { 
    if (strcmp(argv[2], "bin")) { 
    binary_decimal(); 
      }} 
} 
/* Other if statements for number systems to come*/ 
int binary_decimal(char *n) 
/* Function to convert binary to decimal.*/ 
{ 
    char bin; int dec = 0; 
    while (bin != '\n') { 
    sscanf (argv[3],"%d",&num); 
    if (bin == '1') dec = dec * 2 + 1; 
    else if (bin == '0') dec *= 2; } 
    printf("%d\n", dec); 
} 
+1

'strcmp()'如果字符串相等,則返回0 ..您檢查字符串是否*不等於*。 – FatalError 2014-09-30 15:58:19

+1

...並且我在這段代碼中讀取'argv []'時遇到了問題,主要是因爲它不是'binary_decimal'的參數,而是以某種方式出現在它的函數體中。 – WhozCraig 2014-09-30 15:58:59

+0

是的,我知道這個代碼有幾個問題,這就是爲什麼我問。 – Carlo 2014-09-30 16:03:40

回答

0

線條

if (strcmp(argv[1], "dec")) { 
    if (strcmp(argv[2], "bin")) { 
    binary_decimal(); 
      }} 

需要被

if (strcmp(argv[1], "dec") == 0) { // Add == 0. strcmp returns 0 when the strings are equal 
    if (strcmp(argv[2], "bin") == 0) { // Add == 0 
    binary_decimal(argv[3]); // Add the argument in the function call 
      }} 

問題binary_decimal

int binary_decimal(char *n) 
{ 
    char bin; int dec = 0; 
    while (bin != '\n') {  // bin has not been initialized. 
    sscanf (argv[3],"%d",&num); // argv is not visible in this function. 
           // Also, num is not a variable. 
    if (bin == '1') dec = dec * 2 + 1; 
    else if (bin == '0') dec *= 2; } 
    printf("%d\n", dec); 
} 

這是一個改進版本:

int binary_decimal(char *n) 
{ 
    char* cp = n; 
    int dec = 0; 

    // Step through the given argument character by character. 
    for (; *cp != '\0'; ++cp) 
    { 
     // The characters have to be 0 or 1. 
     // Detect invalid input. 
     if (*cp != '\0' && *cp != '1') 
     { 
     // Deal with invalid input 
     } 

     // Accumulate the decimal value from the binary representation 
     dec = 2*dec + (*cp-'0'); 
    } 

    return dec; 
}