PDA

View Full Version : fgets doubt



masterof14
November 7th, 2009, 08:11 PM
Hi

I'm writing a script for my programming classes and I'm having a small problem maybe someone can help me

somewhere in my script comes:

while(fgets(line, 1024, stdin) != NULL)
{
sscanf(line, "%s", command);
if(strcmp(command, "exit")==0)
{
/*MY DOUBT*/;
}
else

/*some more script*/
} /* end of while*/

printf("Goodbye!");

When I write "exit" he should exit the while cycle. I already tried
return (-1)
return(0) and
return EOF

one more thing: I'm not allowed to use the break command. Any clue?

Can+~
November 7th, 2009, 08:51 PM
one more thing: I'm not allowed to use the break command. Any clue?

Assuming that your code works fine, how about adding a boolean value and just flip it?


#include <stdbool.h>

...

bool running=true;
while(... && running)
{
...
...
if (...)
running = false;
}

masterof14
November 7th, 2009, 09:11 PM
well I'm only allowed to use ANSI C :S

Can+~
November 7th, 2009, 09:22 PM
char running = 1;
while(... && running)
{
...
...
if (...)
running = true;
}

Same thing, stdbool is just a typedef and two #defines (true 1 and false 0).

Arndt
November 7th, 2009, 09:51 PM
Hi

I'm writing a script for my programming classes and I'm having a small problem maybe someone can help me

somewhere in my script comes:

while(fgets(line, 1024, stdin) != NULL)
{
sscanf(line, "%s", command);
if(strcmp(command, "exit")==0)
{
/*MY DOUBT*/;
}
else

/*some more script*/
} /* end of while*/

printf("Goodbye!");

When I write "exit" he should exit the while cycle. I already tried
return (-1)
return(0) and
return EOF

one more thing: I'm not allowed to use the break command. Any clue?

If 'break' is the only thing you're not allowed to use, why not use 'goto'?

MindSz
November 8th, 2009, 04:10 AM
How about:


while(fgets(line, 1024, stdin) != NULL)
{
sscanf(line, "%s", command);
if(strcmp(command, "exit")==0)
{
printf("Goodbye!\n");
return 0;
}
else
{
/*some more script*/
} /* end of while*/

If you exit the program when you encounter "exit" then it should work. Instead, if you need to exit to another state of the program, then you can place the code inside a function which returns a value upon completion.

dwhitney67
November 8th, 2009, 04:52 AM
Hi
...
one more thing: I'm not allowed to use the break command. Any clue?

Read this...
http://ubuntuforums.org/showthread.php?t=717011

From your question concerning:


/*MY DOUBT*/;

a simple 'break' statement ought to suffice,

P.S. Oh, you cannot use a break! Well then consider using a flag variable that is either set to a zero (0) or a one (1). Programmers tend to call this a 'semaphore' or a boolean 'flag'.