【问题标题】:Compiling problem with converter of base number基数转换器的编译问题
【发布时间】:2021-01-16 19:22:20
【问题描述】:

我们假设编写一个程序,从 startBase 中获取一个数字 n,并返回 endBase 中的数字。

例如,如果我输入 ./a.out 1 ABCD 16 10 那么程序应该返回

1 has 1 bit(s)
ABCD (base 16) = 43981 (base 10)

下面是我的转换函数

string converter(string num, int base1, int base2){
  int decimal = 0;
  string result = "";
  if(num == "0"){
    return 0;
  }

  for(int i = num.length() - 1; i >=0; i--){
    char current = num[i];
    int e;
    if(current == 'A'||current == 'B'||current == 'C'||current == 'D'||current =='E'||current == 'F'){
      e = (int)current - 55;
    }else{
      e = (int)current - (int)'0';
    }
    decimal = decimal + e*pow(e,base1);
    }

    string strdecimal = to_string(decimal);
    while(decimal > 0){
      result = to_string(decimal%base2) + result;
      decimal = decimal/base2;
    }

    return result;
}


这就是我在主函数中执行它的方式

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

void outputBinary(unsigned int x);
int countBits(unsigned int n);
string converter(string num, int base1, int base2);
  

int main(int argc, char **argv){
  int a = stoi(argv[1]);
  int b = countBits(a);
  string c = converter(argv[2], argv[3], argv[4]);
  
  cout << a << " has " << b << " bit(s)" << endl;
  cout << argv[2] << "(base" << argv[3] << ")" << "=" << c << "(base" << argv[4] << ")" << endl;
  return 0;
}

但是遇到以下问题

bitCounter.cpp:15:14: error: no matching function for call to 'converter'
  string c = converter(argv[2], argv[3], argv[4]);
             ^~~~~~~~~
bitCounter.cpp:8:8: note: candidate function not viable: no known conversion from 'char *' to 'int' for 2nd argument; dereference the argument with *
string converter(string num, int base1, int base2);

我该如何解决?另外,我的转换功能是否在做它应该做的事情? 谢谢

【问题讨论】:

  • argv 数组是一个字符串数组。您将这些字符串传递给 converter 函数,而无需转换为函数期望的 int 参数。
  • 至于“我的转换函数是否在做它应该做的事情”,这就是为什么你应该学习如何使用调试器。

标签: c++ hex converters


【解决方案1】:

argv是一个(c-string)数组,所以需要将字符串转换为ints。您可以使用std::atoi 执行此操作。 祝你好运!

【讨论】:

  • 这是一个 C 函数,还有其他简单的方法可以做到这一点。
【解决方案2】:

argvchar 数组的数组。因此,您必须将其转换为 int 。所以使用这个代码:

string c = converter(argv[2], std::stoi(argv[3]), std::stoi(argv[4]));

这里std::stoistd:: string 作为参数。所以 char 数组转换为 std:: string 然后转换为 int 。转换为:

  • long 使用 std::stol
  • long long 使用 std::stoll

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2015-01-22
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多