Originally Posted by
holler
I thought that fgets() is used to read from files or when reading input with spaces (John Smith, etc.).
It's used to read an entire line from a stream (assuming the buffer is large enough to contain the entire line). As you've already shown, it can be called using stdin as the stream.
It may be a good idea to read strings with the spaces; what if there's a John Smith and a John Higgins?
Be aware that fgets() stores the newline (if there's room), which must be removed if you don't need it in the string.
Originally Posted by
holler
Tried to replace scanf() from my code with fgets(worker[i].name, NUM, stdin) to find out that it loops through it only once. The second time it skips it and asks to enter the desk number.
The newline left over from entering the number at the end of the first iteration is read by fgets() at the beginning of the second. This is one of the problems with mixing formatted- (e.g. scanf() ) and line-oriented (e.g. fgets() ) input.
If what you have is suitable for your purposes, then it should be okay. I'll just offer an example for your consideration:
Code:
#include <stdio.h>
#include <string.h>
#define STRLEN 64
#define WORKERS 3
struct office
{
char name[STRLEN];
int desk;
};
int main(void)
{
struct office worker[WORKERS];
char input[STRLEN];
int i;
for(i = 0; i < WORKERS; i++)
{
printf("Name %d: ", i + 1);
fflush(stdout);
fgets(worker[i].name, sizeof(worker[i].name), stdin);
worker[i].name[strcspn(worker[i].name, "\n")] = '\0'; /* remove newline */
printf("Desk Number: ");
fflush(stdout);
fgets(input, sizeof(input), stdin);
if(sscanf(input, "%d", &worker[i].desk) != 1)
worker[i].desk = -1; /* error condition, handle however you'd like */
}
printf("\n\n");
for(i = 0; i < WORKERS; i++)
{
printf("%s sits at desk %d\n", worker[i].name, worker[i].desk);
}
return 0;
}
Note that both inputs are read as strings. The second one (to read the desk number) uses sscanf() to parse the input string for the number. If a number is not found, it defaults to a value of -1.