Reputation: 29
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
Reputation: 2610
Key issues:
i
twice per loop. Just use [i+1]
to store the NUL
.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