Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Help with my program

+6 votes
asked Nov 14, 2020 by Vicent Cotaina Bertó (390 points)
edited Nov 17, 2020 by Vicent Cotaina Bertó
I have to make a program that when the user introduces a number clasificates it in positive y negative and if the user inserts a ',' it change to a '.'. Actually it only accept positive numbers but no negatives and decimals I have te following code and i have to do it with "switch" estructure:

int main()
    int p=0,n=0,k=0;
    float positivos[p] = {},negativos[n] = {};
    float valor, SumaPositivos=0, SumaNegativos=0,prueba=0;
    char caracter;
    cout << "Introduce your money movemente: " ;
    while (valor!=0)
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '\n':
                    positivos[p] = prueba;
                    std::cout << prueba << "\n";
                    negativos[n] = prueba;
                    std::cout << prueba << "\n";
                cout << "No valid character, insert numbers.";
                caracter=' ';


1 Answer

0 votes
answered Nov 16, 2020 by Peter Minarik (88,130 points)
You have shared the same code before where you wrongly initialize your arrays. I've shown you how to do it correctly, but you still keep posting the same mistakes: http://question.onlinegdb.com/8577/need-help-with-my-code

Why do you ask for help if you do not take the advice how to fix your code?

If this is a school assignment, people are happy to help you. But it should be you who solves it, not someone else.
commented Nov 17, 2020 by Vicent Cotaina Bertó (390 points)
The arrays work correctly so I dont need to change them.
commented Nov 17, 2020 by Peter Minarik (88,130 points)
As stated before, you're accessing elements on a zero-sized array which can lead to memory corruption.

Your code works by coincidence. It may not crash with the inputs you provide it but it may do so any time in the future. (Especially if it would be compiled with code optimization.)

Also, memory corruption can occur without a crash. Tracking down memory corruptions is quite tricky.

Save yourself the trouble and do not try to use a code that's faulty by design.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.