1

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

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.