Adding elements to an array

Im having a really hard time figuring out a function to add an element to an array. No vectors. Just arrays.

I set it to a CONST of 100 and get user input to add a string item to the array. So i need help figuring out a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>

int main()
{
    const std::size_t MAX_SIZE = 100 ;

    std::string my_array[MAX_SIZE] ;
    std::size_t curr_size = 0 ; // current logical size

    // add elements to the array
    const std::string sentinel = "QUIT" ;
    std::cout << "enter strings one by one up to a maximum of " << MAX_SIZE << " strings.\n"
              << "enter '" << sentinel << "' (without the quotes) to end input.\n" ;

    std::string user_input ;
    while( curr_size < MAX_SIZE &&
           std::cout << "? " && std::getline( std::cin, user_input) &&
           user_input != sentinel )
    {
        my_array[curr_size] = user_input ;
        ++curr_size ;
    }

    // print out the elements that were added
    std::cout << "the strings are:\n--------------\n" ;
    for( std::size_t i = 0 ; i < curr_size ; ++i ) std::cout << i << ". " << my_array[i] << '\n' ;
}
check your messages!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void display_list( const string grocery_list[], int current_list_size ); // *** const added

// *** current_list_size: pass reference 
void add_item( string grocery_list[], int& current_list_size, string grocery_item );

string get_item_name( const string grocery_list[], int current_list_size, int index ); // *** const added

void add_item( string grocery_list[], int& current_list_size, string grocery_item )
{
    /*
    for (int i = 0; i < current_list_size; i++)
    {
    current_list_size++;
    grocery_list[current_list_size - 1] = grocery_item;
    }
    */

    grocery_list[current_list_size] = grocery_item;
    ++current_list_size ;
}

string get_item_name( const string grocery_list[], int current_list_size, int index )
{
    if( index >= 0 && index < current_list_size ) return grocery_list[index] ;
    else return "invalid index" ;

    /*
    for( int i = 0; i < current_list_size; i++ )
    {
        current_list_size = index + 1;
        cout << grocery_list[current_list_size];
    }
    */

    // cout << "INVALID";

}

void display_list( const string grocery_list[], int current_list_size )
{
    for( int i = 0; i < current_list_size; i++ )
    {
        cout << grocery_list[i] << '\n' ; // *** new line added
    }
    cout << /* endl */ '\n' ;
}
Topic archived. No new replies allowed.