【问题标题】:I'm trying to use stoi(), but the compiler is trying to give me replacements and won't compile我正在尝试使用 stoi(),但编译器试图给我替换并且不会编译
【发布时间】:2015-03-03 17:19:29
【问题描述】:

我只是通过 HackerRanks 练习我的 C++,我正在做这个问题:

问题陈述

给你一个整数 N。找出这个数字中的数字 精确除以 N(除以 0 作为余数)并显示 他们的计数。对于 N=24,有 2 个数字 - 2 和 4。这两个 数字正好整除 24。所以我们的答案是 2。

注意

如果相同的数字在不同的位置重复两次,它应该 被计算两次,例如,对于 N=122,2 正好除以 122 并且出现在 个位和十位。所以对于这种情况,我们的答案是 3。除法 0 未定义。输入格式

第一行包含 T(测试用例数),然后是 T 行 (每个都包含一个整数 N)。

约束 1≤T≤15 0

这是我的程序:

    1 #include <cmath>
    2 #include <string>
    3 #include <iostream>
    4 #include <cstdlib>
    5 using namespace std;
    6 void checkDigits(string);
    7 int main (){
    8   string val;
    9   int count = 0, i;
   10
   11   cin >> i;
   12   for (int j = 1; j <= i; j++){
   13     cin >> val;
   14     checkDigits(val);
   15   }
   16   return 0;
   17 }
   18
   19 void checkDigits(string s){
   20   int len, count = 0;
   21   int full, digit;
   22
   23   len = s.length();
   24   for(int i = 0; i < len; i++){
   25     full = stoi(s);
   26     digit = stoi(s[i]);
   27     if(full % digit == 0)
   28       count++;
   29   }
   30   cout << count;
   31 }

什么会导致我的编译器给我这个错误?

hackerrank2.cpp:在函数‘void checkDigits(std::string)’中: hackerrank2.cpp:26:20: 错误: 重载 'stoi(char&)' 的调用是 模棱两可的数字 = stoi(s[i]); ^hackerrank2.cpp:26:20:注意:候选人是:在/usr/include/c++/4.8/string:52:0 包含的文件中, 来自hackerrank2.cpp:2:/usr/include/c++/4.8/bits/basic_string.h:2823:3:注意:int std::stoi(const string&, std::size_t*, int) stoi(const 字符串& __str, size_t* __idx = 0, int __base = 10) ^ /usr/include/c++/4.8/bits/basic_string.h:2823:3:注意:未知 参数 1 从 ‘char’ 到 ‘const string& {aka const std::basic_string&}’ /usr/include/c++/4.8/bits/basic_string.h:2926:3:注意:int std::stoi(const wstring&, std::size_t*, int)
stoi(const wstring& __str, size_t* __idx = 0, int __base = 10) ^ /usr/include/c++/4.8/bits/basic_string.h:2926:3:注意:未知 将参数 1 从“char”转换为“const wstring& {aka const std::basic_string&}'

【问题讨论】:

    标签: c++ string c++11


    【解决方案1】:

    std::stoi() 作用于字符串,而不是字符;没有接受char 的std::stoi() 重载,这就是编译器告诉你的。 (请注意,列出的原型将const std::string &amp; 和const std::wstring &amp; 作为它们各自的第一个参数。char &amp; 不能隐式转换为其中任何一个,因此编译器无法选择它应该使用的重载,因为两者都不起作用。)

    如果你知道字符是一个数字,那么你可以使用这个简单的函数:

    inline int ctoi(char c)
    {
        return c - '0';
    }
    

    (或者直接内联:digit = s[i] - '0';)

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 2023-04-08
      • 2015-07-03
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多