I'm currently trying to read a line from stdin using fgets() but i'm getting a segmentation fault (i'm not geting the segmentation fault anymore, please see edit)
int main(void)
{
char selection;
string firstName = NULL;
printf("[A]dd a new client \n");
printf("[D]isplay all clients \n");
printf("[I]ncome Average for all clients \n");
printf("[Q]uit \n");
selection = fgetc(stdin);
printf("\n");
switch (selection) {
case 'A':
printf("First name: ");
fgets(firstName, MAXNAMESIZE, stdin);
printf("\n");
...
}
}
This is the compiler's output:
[A]dd a new client
[D]isplay all clients
[I]ncome Average for all clients
[Q]uit
A
First name: Segmentation fault
Thank you!!
Edit:
i've changed the code like this:
int main(void)
{
char selection;
string firstName;
printf("[A]dd a new client \n");
printf("[D]isplay all clients \n");
printf("[I]ncome Average for all clients \n");
printf("[Q]uit \n");
selection = fgetc(stdin);
printf("\n");
switch (selection) {
case 'A':
if ((firstName = malloc(MAXNAMESIZE * sizeof(char))) == NULL)
return 1;
printf("First name: ");
fgets(firstName, MAXNAMESIZE, stdin);
printf("\n");
...
}
}
But now i'm not able to enter any name, the program just ends. This is the output:
~/workspace/ $ ./test
[A]dd a new client
[D]isplay all clients
[I]ncome Average for all clients
[Q]uit
A
First name:
~/workspace/ $
string
? – tkauslchar*
(typedef char* string
) – Santiago AguilarNULL
. i tried usingstring firstName;
andstring firstName = " ";
but in the first casefirstName
is uninitialized and in the second i also get a segmentation fault – Santiago Aguilar