Reputation: 8962
in my application, i'm trying to achieve something like this:
i have:
flow:
maybe something like this?(pseudo code):
int main(int argc, char *argv[])
{
get parameters();
int fslen = data size
char *c = (char *)malloc(fslen);
fgets(c, fslen, stdin);
while((c != null) || (c != Terminate code?))
{
do calculations with int c;
clear c;
}
return 0;
}
or is their a better approach?
or is it just bad practice to do things this way? if so, please explain
Upvotes: 0
Views: 9208
Reputation: 2097
There's really not any better way, at least as far as I'm aware, to read and parse line input than to read and parse line input.
By default, stdin should be blocking, so your 'waiting' criterion should be taken care of automagically.
You will, however, need two loops if you're going to be reading lines and then parsing the lines for codes:
int main(int argc, char *argv[])
{
/* initial parameter/buffer setup goes here */
while (fgets(buffer, bufferlen, stdin)) {
for (c = buffer; *c != '\0' && *c != terminatingcode; c++) {
/* calculations go here! ... they sure do! </homer> */
}
if (*c == terminatingcode || ferror(stdin))
break;
}
}
Be aware that fgets() can "fail" here for perfectly innocent reasons, and you need to become familiar with feof() and ferror() to make sure you're using the interface correctly; I'm unsure whether my use in the code above is consistent with what you want/need the code to do.
Upvotes: 2