Stopping input with CTRL+D [Archive] - C Board

PDA

View Full Version : Stopping input with CTRL+D


SirKnightTG
09-19-2003, 03:39 PM
I'm trying to write a program in linux that will allow me to enter a word then a space then a number. Then after I hit enter it will let me do this again and again. Now I need to be able to stop this so I want it to stop taking input and do some processing when I hit CTRL+D. Something like this:

joe 30
bob 40
jill 20
(CTRL+D pressed)
(now do stuff with the data just entered)


But I can't seem to get it to work without getting a core dump. BTW im writing this in C not C++. Any one know how I can do this? I sorry I don't have the code I have, I left it on another computer that I can't access right now. Thanks for any suggestions. I'm rather new at linux developing.

Kyro
09-20-2003, 02:00 AM
Ctrl+D == EOF

use getchar to get the characters from input and scan for EOF character.

input is buffered so you can use a while loop with getchar to get a input string.

twm
09-20-2003, 07:54 AM
Sounds like you need an fgets/sscanf pair and a linked list:

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
char name[100];
int number;
struct node *next;
} *link;

int main ( ) {
char buffer[BUFSIZ];
link list;
link scratch;

list = 0;
while (fgets(buffer, sizeof buffer, stdin) != NULL) {
if ((scratch = malloc(sizeof *scratch)) == NULL)
break;
if (sscanf(buffer, "%s%d", scratch->name, &scratch->number) != 2)
break;
scratch->next = list;
list = scratch;
}
for (scratch = list; scratch != NULL; scratch = scratch->next)
printf("%s -- %d\n", scratch->name, scratch->number);

return 0;
}

SirKnightTG
09-20-2003, 11:52 AM
Great, thanks a lot guys! I was able to get this to work using visual C++ in a console app but with linux it seemed different. There were some functions I used before that my linux compiler did not know about so I wasn't sure what to do. :) It's been ages since I used C last so I forgot some of the functions. Thanks!

twm
09-20-2003, 11:58 AM
>There were some functions I used before that my linux compiler did not know about
Sounds like a case of Microsoftitis. Take two of these (ISO/IEC 9899:1999) and call me in the morning. I also recommend a strict regimen of Linux use for the next 50 years. Try to stay off Windows as well, it's bad for your mental health. :)