繁体   English   中英

错误:来自 &#39;__gnu_cxx::__alloc_traits 的无效转换<std::allocator<char> , char&gt;::value_type&#39; {aka &#39;char&#39;} 到 &#39;const char*&#39; [-fpermissive]

[英]error: invalid conversion from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'const char*' [-fpermissive]

面临错误,我正在尝试将 char 值转换为 int 然后将它们平方。我尝试使用 atoi() 和 sscanf() 但我仍然面临这个错误

#include <stack>
#include<iostream>
#include<cmath>
#include<string>
#include <sstream> 

using namespace std;
int main(){
        int n;
        std::cin>>n;
        long long int num = n;
        while(num != 1){
            stack<char>s;
            string strnum = to_string(num);
            for(int i=0;i<strnum.size();i++){
                s.push(strnum[i]);
            }
            num = 0;
            while(!s.empty()){
                int x=0;
                //sscanf(s.top(),"%d",&x);
                x = atoi(s.top());
                num += (x*x);
                std::cout << x << std::endl;
                s.pop();
            }
    cout<<"num is : "<<num<<endl;
        }

        std::cout<<1;

}

在这次通话中

x = atoi(s.top());

一个char类型的对象作为参数传递给函数 atoi ,该函数需要一个char *类型的参数。 注意这个栈被定义为一个单独字符的栈。

stack<char>s;

你可以写

x = s.top() - '0';

如果你想得到一个存储在源字符串中的数字压入堆栈然后写

        const int Base = 10;
        int multiplier = 1;
        num = 0;
        while(!s.empty()){
            int x=0;
            //sscanf(s.top(),"%d",&x);
            x = s.top() - '0';
            num += multiplier * x;
            multiplier *= Base;
            //...

如果你想以相反的顺序获取数字然后写

        const int Base = 10;
        num = 0;
        while(!s.empty()){
            int x=0;
            //sscanf(s.top(),"%d",&x);
            x = s.top() - '0';
            num = Base * num + x;
            //...

请记住,标准函数std::stoi可以将字符串转换为数字。

您应该使用 unsigned int 类型的对象。 否则用户可以输入一个负数,它将被错误地处理。 这是一个演示程序

#include <iostream>
#include <string>
#include <stack>

int main() 
{
    unsigned int n;
    
    while ( std::cin >> n && n != 0 )
    {
        std::string strnum = std::to_string( n );
        std::stack<char> s;
        
        for ( char c : strnum ) s.push( c );
        
        unsigned long long int num = 0;
        
        while ( !s.empty() )
        {
            unsigned int digit = s.top() - '0';
            num += digit * digit;
            s.pop();
        }
        
        std::cout << "num = " << num << '\n';
    }

    return 0;
}

如果输入数字123那么它的输出可能看起来像

num = 14

即 1 * 1 + 2 * 2 + 3 * 3 == 14。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM