简体   繁体   中英

how to fill array of strings using user input

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM