gpt4 book ai didi

c++ - 我正在尝试使用 stoi(),但编译器正在尝试给我替换并且不会编译

转载 作者:行者123 更新时间:2023-11-30 01:15:52 30 4
gpt4 key购买 nike

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

Problem Statement

You are given an integer N. Find the digits in this number that exactly divide N(division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits − 2 & 4. Both of these digits exactly divide 24. So our answer is 2.

Note

If the same number is repeated twice at different positions, it should be counted twice, e.g., For N=122, 2 divides 122 exactly and occurs at ones' and tens' position. So for this case, our answer is 3. Division by 0 is undefined. Input Format

The first line contains T (number of test cases) followed by T lines (each containing an integer N).

Constraints 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: In function ‘void checkDigits(std::string)’: hackerrank2.cpp:26:20: error: call of overloaded ‘stoi(char&)’ is ambiguous digit = stoi(s[i]); ^ hackerrank2.cpp:26:20: note: candidates are: In file included from /usr/include/c++/4.8/string:52:0, from hackerrank2.cpp:2: /usr/include/c++/4.8/bits/basic_string.h:2823:3: note: 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: note: no known conversion for argument 1 from ‘char’ to ‘const string& {aka const std::basic_string&}’ /usr/include/c++/4.8/bits/basic_string.h:2926:3: note: 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: note: no known conversion for argument 1 from ‘char’ to ‘const wstring& {aka const std::basic_string&}’

最佳答案

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

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

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

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

关于c++ - 我正在尝试使用 stoi(),但编译器正在尝试给我替换并且不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791914/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com