命令行参数中的 2 位数字仅作为一位数字处理

2 Digit Numbers in Command Line arguments Treated only as a Single Digit

这是我 average.cpp 中的代码:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[]) {
  int total = 0;
  for(int i=1; i<argc; i++) {
    char cnum = *argv[i];
    string snum = "";
    snum += cnum;
    total += stoi(snum);
  }

  cout << "The average is " << total/(argc-1) << endl;

  return 0;
}

当我 运行 ./average 3 5 33 时,答案应该四舍五入为 13,但我却得到 3。当我 运行 ./average 3 5 44 时,答案应该四舍五入为 17,但我得到 4。我知道只有参数的第二个数字被忽略了,但我不确定如何包含第二个数字。

以下有帮助吗?

  int total = 0;
  for(--argc; argc > 0 ; --argc) total += atoi(argv[argc]);
char cnum = *argv[i];

这是取参数的第一个字符。您不仅需要第一个字符,还需要 whole 参数。所以只写:

    const std::string snum = argv[i];
    total += std::stoi(snum);

(你可以这样写:

    total += std::stoi(argv[i]);

这依赖于从 const char*std::string 的隐式转换 - 但在调试时命名中间值通常很有帮助。)