Code ". exe" stopped working

Asked

Viewed 53 times

2

When adding new emails appears the message:

project-Email2.exe has stopped working

int op = 0, quant = 1;
string nomeEmail[quant][2];

while(op != 5){ 
cout << "Selecione a opção desejada\n[1] - Inserir novo nome e e-mail\n[2] - Listar e-mails\n[3] - Consultar e-mail\n";
cout << "[4] - Deletar e-mail\n[5] - Finalizar programa\n";
cin >> op;
        if(op == 1){            
            cout << "\n\nQuantos e-mails você deseja inserir?\n";
            int n;
            cin >> n;
            for(int i = 0; i < n; i++){
                cout << "Insira o novo endereço de e-mail, e, em seguida, o nome do usuário:\n";
                cin >> nomeEmail[quant - 1][0] >> nomeEmail[quant - 1][1];
                cout << "Este é o e-mail de número: " << quant << "\n\n";
                quant++;
        }}

Código dando erro

1 answer

1


You are creating the array (the way it is done in C and not C++) right at the beginning of the code with the size 1. Then you try to fill this array n times, that is, after doing it the first time already filled the array and any additional access will potentially give problem, even breaking the application because it invades the memory that is not reserved for this. So the solution is to declare the array only after you already know what the value of n, then you can place the number of positions needed to fill. Forget all this variable quant She’s trouble, she just needs n and i.

#include <iostream>
using namespace std;

int main() {
    int op = 0;
    while (op != 5) { 
        cout << "Selecione a opção desejada\n[1] - Inserir novo nome e e-mail\n[2] - Listar e-mails\n[3] - Consultar e-mail\n";
        cout << "[4] - Deletar e-mail\n[5] - Finalizar programa\n";
        cin >> op;
        if (op == 1) {            
            cout << "\n\nQuantos e-mails você deseja inserir?\n";
            int n;
            cin >> n;
            string nomeEmail[n][2];
            for (int i = 0; i < n; i++) {
                cout << "Insira o novo endereço de e-mail, e, em seguida, o nome do usuário:\n";
                cin >> nomeEmail[i][0] >> nomeEmail[i][1];
                cout << "Este é o e-mail de número: " << i + 1 << "\n\n";
            }
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Oops, Maniero! Thanks for the reply! I implemented your suggestion to take out Quant and my code is much simpler.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.