I’m working on a C program where I want to user to type the following format into stdin:
<integer1> <string> <optional-integer2>
I have the program working when integer2 is always there. for example “3 birds 2” will run fine. But every way I have tried just results in the programming hanging if it recieves input without the optional part, like “5 cats”. How can I have the program check to see if the optional integer exists, and skip reading it if it doesn’t?
Here is what I am working with:
int main(){
//help();
size_t size = 20;
ssize_t len;
long num1 = 1111;
long num2 = 2222;
char *word;
char chunks[3][20];
printf("(enter command): ");
char delimeter;
char *cp;
int i;
while(1){
cp = chunks[0];
delimeter = ' ';
for(i = 0; i < 3; i++){
if(i == 2)
delimeter = '\n';
cp = chunks[i];
len = getdelim(&cp, &size, delimeter, stdin);
*(cp+(len - 1)) = '\0';
printf("cp: '%s'\n", cp);
}
for (i = 0; i < 3; i++){
printf("chunks[%d]: '%s'\n", i, chunks[i]);
}
1 Answer