I’m having trouble displaying the names of people over 18

Asked

Viewed 559 times

3

/*Escreva um programa que receba o nome, profissão e a idade de 10 pessoas, calcule e imprima a quantidade de pessoas maiores de idade (idade >= 18 anos) e seus respectivos nomes.*/

#include <iostream>
#include <locale.h>
#include <string.h>
#include <stdio.h>

using namespace std;

int main()
{
    setlocale(LC_ALL, "portuguese");
    int idade,cont=0;
    char pro[23];
    char nome[23];
    char nr[23];


    for (int i=0; i<2;i++){
        cout << "Digite o seu " << i+1 <<"º nome, profissão e idade: ";
        scanf("%s", &nome[i]);
        scanf("%s", &pro[i]);
        scanf("%d", &idade);
        if (idade >= 18){
            cont++;
            strcpy(nr[i],nome[i]);
        }
    }

    cout << "número de pessoas maior de 18 anos: " << cont << endl;

    for (int i=0;i<2;i++){
        cout << "nome: " << nr[i] << endl;
    }

    return 0;
}
  • Good evening, don’t use tags that don’t have to do with your code, C#, C++ and C are different things. Consider this a constructive criticism :)

1 answer

3


If you are using C++, use the language, do not mix with C. Then use the cin for data entry and string to store texts. There it is easier.

One of the problems is that it seems that you are wanting to keep up to 23 names, but are actually keeping a name with up to 23 characters, since a string in C is a array of char. Changing to the type string which is already a text, the array is being used to store a list of names.

Also the copy is being made without much discretion (besides using C). I copied what I needed, but at the bottom of the list I kept all the elements, although some would get garbage, since there was no copy of the name. This logic needed to be changed.

In real code I would change several other things. I would create a structure to store all the data together, I would use a Vector in place of array, among other small changes and reorganizations.

Stayed like this:

#include <iostream>
#include <locale.h>
#include <string.h>
#include <stdio.h>

using namespace std;

int main() {
    setlocale(LC_ALL, "portuguese");
    int idade, cont = 0;
    string pro[23];
    string nome[23];
    string nr[23];
    for (int i = 0; i < 2; i++) {
        cout << "Digite o seu " << i + 1 <<"º nome, profissão e idade: ";
        cin >> nome[i];
        cin >> pro[i];
        cin >> idade;
        if (idade >= 18) nr[cont++] = nome[i];
    }
    cout << "número de pessoas maior de 18 anos: " << cont << endl;
    for (int i = 0; i < cont; i++) cout << "nome: " << nr[i] << endl;
}

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

  • This code will fail in cases where the name has more than one word. For example: Ricardo Rodrigues

  • It’s another thing I’d arrange, but I didn’t want to complicate it for him.

Browser other questions tagged

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