mercredi 22 avril 2015

Passing values to char array in a function

I am trying to use a function to sort through a char array full of words. The current issue I am having is that in my sortNames function I am getting the error, "expression must be a modifiable lvalue" at the part below

hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;

I am guessing that its because I am trying to pass values through an array for some reason. I am struggling with understanding references and pointers and the such, and I imagine that is hurting me here as well. Any help with this would be fantastic, thank you in advance.

Here is my current code...

#include <iostream>
#include <string>

using namespace std;

char nameArr[20][15];           // array to store the 20 values
int val = 0;                    // variable to pass values to the array
int x = 0;                      // loop counter outside functions

//Function prototypes
void getNames(char (&nameArr)[20][15], int &val);
void sortNames( char(&nameArr)[20][15]);

//getNames Function
void getNames(char (&nameArr)[20][15], int &val)
{
    int i = 0;                  // loop counter

    cout << "Awesome, now lets input those names...\n" << endl; 

    for (i = 0; i < val; i++)
    {
        cout << "\nNAME " << i+1 << ": " << ' ';
        cin >> nameArr[i];
    }

    cout << "\n\n\nThese are the names that you inserted:\n" << endl;

    for (i = 0; i < val; i++)
    {
         cout << nameArr[i] << "\n" << endl;
    }
}

// sortNames function
void sortNames( char(&nameArr)[20][15])
{
    int n = 15;             // max length of word
    int ii = 0;             // loop counter
    int jj = 0;             // other counter
    string hold;            // holding array

    for (int ii = 0 ; ii < n ; ii++) 
    {   
         for (int jj = ii + 1; jj < n; jj++) 
        {
             if (nameArr[ii] > nameArr[jj])
            {
                hold = nameArr[ii];
                nameArr[ii] = nameArr[jj];
                nameArr[jj] = hold;
            }
        }
    }
}


int main()
{
    cout << "NAME SORTER!\n\nPlease enter in the amount of names you wish to enter: " << ' ';
    cin >> val;

    getNames(nameArr, val);

    cout << "\n\n\nAlright, lets sort now..." << endl;

    sortNames(nameArr);

    cout << "\nHere are the results:\n" << endl;

    for (x = 0; x < val; x++)
    {
         cout << nameArr[x] << "\n" << endl;
    }

    system("pause");
 }

Aucun commentaire:

Enregistrer un commentaire