Home > Software engineering >  How to use user input to decide which element in a array is going to show?
How to use user input to decide which element in a array is going to show?

Time:12-01

I'm trying to make something like a digital phonebook. For example. If the user type in 2 I want the second element in my array to show. I tought that if I used cin >> to decide the value of int i it would work. But It only shows the first element in my array.

This is my third week in programming so please be patient. :)

I put all of my code below, if anything else is wrong or if I made som typos please tell me!

#include <iostream>
#include <string>
using namespace std;

struct telefonbok {
    string namn;
    string arbetsplats;
    int nummer;
};

int main()
{ 
    cout << "Beas phonebook" << endl;
    cout << "Mamma - 1" << endl;
    cout << "Pappa - 2" << endl;
    cout << "Emil - 3" << endl;
    cout << "Hugo - 4" << endl;
    cout << "Matilda - 5" << endl;

    telefonbok Beas[5] = {
        {"Mamma", "ICA Maxi", 707397136},
        {"Pappa", "Granarolo", 705174881},
        {"Emil", "BH Bygg AB", 700726477},
        {"Hugo", "SeSol", 700357692},
        {"Matilda", "Hedebyskolan", 762095177}
    };
    
    int i;
    cout << "Type in the number of the contact you want to access:" << endl;
    cin >> i;

    for (int i = 0; i < 5;i  )
    {
        cout << "Name: " << Beas[i].namn << endl;
        cout << "Workplace: " << Beas[i].arbetsplats << endl;
        cout << "Number: " << Beas[i].nummer << endl;
    }

}

CodePudding user response:

If you want to show only one entry from the phone book, then why have you written a loop? Try this instead

int i;
cout << "Type in the number of the contact you want to access:" << endl;
cin >> i;

// show entry at position i
cout << "Name: " << Beas[i - 1].namn << endl;
cout << "Workplace: " << Beas[i - 1].arbetsplats << endl;
cout << "Number: " << Beas[i - 1].nummer << endl;

Notice I subtract one from the number entered, this is because in C arrays start at zero, but most people start counting at one.

Also you should add a check to see if the number entered is actually in the array. If the number entered is too big or too small then this code will likely crash.

CodePudding user response:

The code chunk of

    cin >> i;

    for (int i = 0; i < 5;i  )
    {
        cout << "Name: " << Beas[i].namn << endl;
        cout << "Workplace: " << Beas[i].arbetsplats << endl;
        cout << "Number: " << Beas[i].nummer << endl;
    }

reads in the value of i correctly via cin, however, your code loops the first 5 elements and displays values for them. Independently of what i was (2) in this case, at the start of the for loop a new variable called i is created and initialized to 0, shadowing the i you have created earlier and increments it after each steps, so you display the first element, then the second, then the third, then the fourth and finally the fifth.

C is zero-indexed, which means that the first element of Beas is 0. Instead of the loop you need to validate your input and get the corresponding element:

    cin >> i;
    int size = sizeof(Beas)/sizeof(Beas[0]);

    if (((i - 1) >= 0) && ((i - 1) < size)) //5 is your 
    {
        cout << "Name: " << Beas[i - 1].namn << endl;
        cout << "Workplace: " << Beas[i - 1].arbetsplats << endl;
        cout << "Number: " << Beas[i - 1].nummer << endl;
    }
    else
    {
        //Index would be out of bounds, you may handle that here
    }

Explanation:

  • we read the value of i
  • we calculate the size of the array in terms of number of elements by dividing the actual size of the array with the size of its first element (the other elements having the same size as the first)
  • we acknowledge that if the user wanted to see the second element, then he/she enters a 2, whereas our first element has an index of 0 and second element has an index of 1, so we subtract 1 of the input to get the correct index
  • we check whether the index is valid in the array
  • if so, then we display the element having that index
  • otherwise we (may) handle the problem, possibly throwing an exception or having some custom logic in order to handle the problem gracefully

Note that it is advisable not to leave the else block empty, because that would hide the error and would cause difficulties during a debug session. The only reason on my part not to implement an error handler there was to avoid confusing you at this point, but, when the task is done, you should consider adding some error handling there.

  • Related