【问题标题】:error: invalid conversion from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'const char*' [-fpermissive]错误:从 '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} 到 'const char*' [-fpermissive] 的无效转换
【发布时间】:2020-07-14 06:54:09
【问题描述】:

面临错误,我正在尝试将 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;

}

【问题讨论】:

  • 检查atoi manual。它需要什么类型的参数,你传递了什么?

标签: c++ data-structures stl stack


【解决方案1】:

在本次通话中

x = atoi(s.top());

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

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2016-01-20
    • 2014-01-16
    • 1970-01-01
    相关资源
    最近更新 更多