从命令行读取并使用sscanf转换为整数

时间:2014-09-30 15:54:35

标签: c scanf

我遇到了将argv [3]作为字符串读取但是将其作为要转换的整数包含在内的问题。我读过strtol可以做到这一点,但sscanf应该足够吗? if strcmp(argv []的原因是,我将在后面添加16和8基数。非常感谢。

 #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 个答案:

答案 0 :(得分: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;
}