在C++中从'字符到'常量字符的转换无效

Invalid conversion from #39;char#39; to #39;const Char*#39; in C++(在C++中从#39;字符到#39;常量字符的转换无效)
本文介绍了在C++中从'字符到'常量字符的转换无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已声明了一个函数(C++)

int products(char num1, char num2, char num3, char num4, char num5);

但是我的编译器给了我这个错误:

Invalid conversion from 'char' to 'const Char*'
error initializing argument 1 of 'int atoi (const char*)'  on line 22

当我尝试将num1num2等作为参数传递给atoi时。

#include<iostream>
#include<string>

using namespace std;

int Product(char num1, char num2, char num3, char num4, char num5);

const string LargeNum = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";

int main(){
int greatestVal = 0;
for(int i = 0; i + 4 <= LargeNum.length(); i++ ){
    if(greatestVal < Product(LargeNum[i], LargeNum[i+1], LargeNum[i+2], LargeNum[i+3], LargeNum[i+4])){
        greatestVal = Product(LargeNum[i], LargeNum[i+1], LargeNum[i+2], LargeNum[i+3], LargeNum[i+4]);
    }
}
cout << greatestVal << endl;
system("PAUSE");
}

int Product(char num1, char num2, char num3, char num4, char num5){
    return (atoi(num1)*atoi(num2)*atoi(num3)*atoi(num4)*atoi(num5));
}

推荐答案

atoi接受const char*(即以空结尾的字符序列)。您为它提供了一个char,因此编译器会抱怨。您如何修复它取决于您正在尝试执行的操作。

我猜您想要将表示数字的字符转换为整数,‘0’转换为0,‘1’转换为1等等。如果是这样,则正确的代码应该是

return (num1 - '0')*(num2 - '0')*(num3 - '0')*(num4 - '0')*(num5 - '0');

这是可行的,因为当您对字符进行算术时,它们会自动转换为整数,还因为字符‘0’到‘9’被保证是按顺序排列的,所以要将数字转换为整数,只需从数字中减去‘0’。

这篇关于在C++中从&#39;字符到&#39;常量字符的转换无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

socks4 with asynchronous boost::asio(带有异步Boost::ASIO的socks4)
Boost ASIO HTTP client POST(增强ASIO HTTP客户端开机自检)
asio::strandlt;asio::io_context::executor_typegt; vs io_context::strand(Asio::strandlt;asio::io_context::executor_typegt;VS io_CONTEXT::Strand)
What#39;s the difference between asio::io_context and asio::thread_pool?(ASIO::IO_CONTEXT和ASIO::THREAD_POOL有什么区别?)
How to use boost::asio with Linux GPIOs(如何在Linux GPIO中使用Boost::ASIO)
Boost asio io_service vs io_context(增强ASIO io_服务与io_Context)