Gafarrell
Gafarrell

Reputation: 29

How append multiple characters to a string in C?

I'm attempting to create a function that will read in a string from user input by way of reading every character off of the inputted line and inserting them into a character array. I have gotten everything correct except for appending the character to the array. I can append the first character, but after that it stops appending and will only save the first character.

void getstr(int maxSize, char string[]){
    char item;
    int i = 0;
    for (int i = 0; i < maxSize; i++) {
        scanf("%c", &item);
        if (item == 0 || item == '\n'){
            return;
        }

        string[i] = item;
        i++;
        string[i] = 0;
    }
}

I call this function through another one which is used for retrieving a song and the artist from the user.

void getSong(char song[], char artist[]){
    printf("Please enter a song: ");
    getstr(100, song);
    printf("Please enter an artist: ");
    getstr(100, artist);
}

Upvotes: 1

Views: 373

Answers (1)

rtx13
rtx13

Reputation: 2610

Key issues:

  1. You're incrementing i twice per loop. Just use [i+1] to store the NUL.
  2. You should loop to i < maxSize-1 to prevent buffer overrun when storing the terminating NUL.
void getstr(int maxSize, char string[]){
    char item;
    int i = 0;
    for (int i = 0; i < maxSize-1; i++) {
        scanf("%c", &item);
        if (item == 0 || item == '\n'){
            return;
        }

        string[i] = item;
        string[i+1] = 0;
    }
}

Upvotes: 2

Related Questions