-3

I am trying to take string user input from the user using c code and then add it to array of strings so that I could have a variable its first component be a word so if the variable called X then X[1] becomes full word which inputted to the array using prompt function like getstring but when I tried the code below it gave me error.

Can anyone help me restructure my code ?

#include <stdio.h>
#include "cs50.h"
#include <string.h>


string get_items();



bool check_items_add = true;

int main()
{
    string units = get_items();
    printf("%s\n", units[1]);
}

string get_items()
{
    string items[] = get_string("Write market item: ");
    while (check_items_add)
    {
        
        items += get_string("Write market item: ");
    }
    return items;
}
Oka
  • 23,367
  • 6
  • 42
  • 53
  • 2
    You can't add to an array with `+=`. – Barmar Sep 04 '22 at 19:17
  • You can't return a local array from a function. See https://stackoverflow.com/questions/11656532/returning-an-array-using-c – Barmar Sep 04 '22 at 19:19
  • Also, the function is declared to return a single string, not an array of strings. You have a big problem understanding the difference between single values and arrays. – Barmar Sep 04 '22 at 19:19

1 Answers1

0

The line

string items[] = get_string("Write market item: ");

does not make sense, because get_string will only give you a single string, not several strings.

I am not sure if I understood your question properly, but if you want to create an array of strings and fill it one string at a time with get_string, then you can do this:

#include <stdio.h>
#include "cs50.h"
#include <string.h>

#define MAX_STRINGS 100

int main( void )
{
    string strings[MAX_STRINGS];
    int num_strings = 0;

    printf( "In order to stop, please enter an empty string.\n" );

    //read strings into array
    for ( int i = 0; i < MAX_STRINGS; i++ )
    {
        strings[i] = get_string( "Please enter string #%d: ", i + 1 );

        //determine whether string is empty
        if ( strings[i][0] == '\0' )
            break;

        num_strings++;
    }

    printf( "You have entered the following %d strings:\n", num_strings );

    //print all strings
    for ( int i = 0; i < num_strings; i++ )
    {
        printf( "%d: %s\n", i + 1, strings[i] );
    }
}

This program has the following behavior:

In order to stop, please enter an empty string.
Please enter string #1: test1
Please enter string #2: test2
Please enter string #3: test3
Please enter string #4: 
You have entered the following 3 strings:
1: test1
2: test2
3: test3
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39