I have this simple code:
#include <stdio.h>
#include <string.h>
struct todolist {
char name[128];
char content[512];
};
void print_item(struct todolist tdl[10]) {
int i;
puts("Which item would you like to get?");
fflush(stdin);
scanf("%d", &i);
printf("the name of the item is %s, and the content is %s \n", tdl[i].name, tdl[i].content);
fflush(stdin);
}
struct todolist create_item() {
puts("Whats the name of the item?");
char thisName[128];
scanf("8s", thisName);
puts("and what is the item?");
char thisContent[521];
scanf("Q2s", thisContent);
struct todolist todo;
strcpy(todo.name, thisName);
strcpy(todo.content, thisContent);
fflush(stdin);
return todo;
}
void print_menu() {
puts("Todolist");
puts("What do you want to do?");
puts("1. Create item");
puts("2. Print item");
}
int main() {
struct todolist tdl[10];
int c;
int i = 0;
while (1) {
print_menu();
c = getchar();
switch ((char) c) {
case '1':
tdl[i] = create_item();
break;
case '2':
print_item(tdl);
break;
}
}
i ;
}
The issue I'm having is that whenever the user picks an option, like create_item
and inputs some stuff, then the loop does an extra iteration before it starts to read input again.
SO the ouput looks like this:
Todolist
What do you want to do?
1. Create item
2. Print item
1
Whats the name of the item?
hu
and what is the item?
hu
Todolist
What do you want to do?
1. Create item
2. Print item
Todolist
What do you want to do?
1. Create item
2. Print item
My guess is that the issue is that getchar reads a newline that is already in stdin, and just skips that iteration.
But I'm not sure. How do I fix this?
CodePudding user response:
Your guess is correct! You should modify the line that allow the user to pick an option.
So, your code:
c = getchar();
has to be changed with this line:
while ((c = getchar()) == '\n');
To be more clear, this loop will iterate and discard all the trailing newline.