Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c++ - invalid conversion from 'int' to 'const char*' [-fpermissive]| (beginner)

When I try to compile my code this error pops out:

invalid conversion from 'int' to 'const char*'

My task is to write a program that calculates the sum of numbers with odd index.

Please don't roast me (I'm learning how to code in c++), and give some tips how to fix it and get my code working.

#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    string text;
    cin >> text;

    int len = text.length(), sum = 0, number = 0, a = 0;

    for (int i = len; i > 0; i++) {
        a = text[i];
        if (i % 2 == 1) {
            number = atoi(a);
            sum = sum + number;
        }
    }
    cout << sum;

    return 0;
}
question from:https://stackoverflow.com/questions/65831210/invalid-conversion-from-int-to-const-char-fpermissive-beginner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your for loop is incorrect because at the first try it starts at out of range index and increases farther. here :

#include <iostream>

using namespace std;

int main()
{
    string text;
    cin >> text;

    int len = text.length(), sum = 0, number = 0, a = 0;

    for (int i = 0; i < len; i++) {
       a = text[i];
       if (i % 2 == 1) {
            number = a - '0';
            sum = sum + number;
        }
    }
    cout << sum;

    return 0;

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...