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

标签 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);
 }

最佳答案

线条

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;
}

关于c - 从命令行读取并使用 sscanf 转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26125080/

相关文章:

c - 如何解决C中的 undefined reference 错误?

c - C堆栈中的递归

c - 获取 unsigned int 中位的整数值

c - 在包含新行的字符串中搜索?

c - C 中 rand() 函数的行为差异

c - 程序在编译快要结束时崩溃

c - 我的程序中的 scanfs 和/或 ifs 有问题(咖啡店)

c - 使用 scanf() c 从标准输入读取文件名

matlab - 将 ASCII 串行数据分离成单独的矩阵

c - 重叠内存最佳实践