我正在尝试使用 stoi(),但编译器试图给我替代品并且不会编译
I'm trying to use stoi(), but the compiler is trying to give me replacements and won't compile
我只是通过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 string& __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&}'
std::stoi()
处理字符串,而不是字符;没有接受char
的std::stoi()
重载,这就是编译器告诉你的。(请注意,列出的原型将const std::string &
和const std::wstring &
作为各自的第一个参数。 char &
不能隐式转换为其中任何一个,因此编译器无法选择它应该使用哪个重载,因为两者都不起作用。
如果您知道字符是数字,则可以使用此简单函数:
inline int ctoi(char c)
{
return c - '0';
}
(或者只是内联:digit = s[i] - '0';
)