I have the following function that should loop and take multiple lines from the user (names and dates). The user needs to enter an empty line to stop the loop.
while ((line = getLineFromUser()) != NULL) {
token = getNameAndDate(&concert, line);
however, when I get to the last line in the loop, the getchar()
waits for the user input (which is good for me, because it means that I finished getting the previous line), but ch
gets '\n'
as soon as I enter the next line (not specifically an empty line). as anyone encountered this before?
Everything else seems to work fine until the last getchar()
.
if needed, I will provide the other functions as well.
this is the getLineFromUser function:
char *getLineFromUser() {
int ch;
char *line;
int logSize, phySize;
logSize = 0, phySize = 2;
line = (char *)malloc(sizeof(char) * phySize);
checkAllocation(line);
while ((ch = getchar()) != '\n' && ch != EOF) {
if (logSize == phySize) {
phySize *= 2;
line = (char *)realloc(line, sizeof(char) * phySize);
checkAllocation(line);
}
line[logSize] = ch; // get char into the str
logSize++;
}
if (logSize == 0) {
free(line);
line = NULL;
} else {
line = realloc(line, sizeof(char) * logSize + 1);
checkAllocation(line);
line[logSize] = '\0';
}
return line;
}
and this is the declaration:
char* getLineFromUser();