W
whisper
Hello: I am trying to write code to read in a bunch of lines from
stdin,
each containing a (variable) number of integers and writing each
integer
in a separate line to stdout.
I came up the code below.
I could not get sscanf to work because it does not increment its
position
on conversion (like scanf does). Is there some workaround for it ?
Please criticize the code below: I have a feeling I am missing a simple
and elegant solution, since the problem is so simple itself.
Moreover, there is a *bug* in the code: what happens when I have a 0 as
a number ?
Reading will stop then. How do I get around that ?
Are my malloc() error statements correct ? In general, is it not better
to state in
the malloc error's before exiting which variables failed to get
malloc'ed ?
#include <stdio.h>
#define MAX 80
int main() {
int i, n;
char *line, **errline, *lineA, *lineB;
line=malloc(MAX*sizeof(char));
errline=malloc(sizeof(*errline));
if ((line == NULL) || (errline==NULL)) {
fprintf(stderr, "Could not allocate memory");
exit(-1);
}
while (fgets(line,MAX, stdin)!=NULL) {
lineA=line;
while ((n=(int)strtol(lineA, errline, 0))!=0) {
printf("%d \n", n);
lineA=*errline;
// printf("Line is now at %s \n",lineA);
}
}
}
stdin,
each containing a (variable) number of integers and writing each
integer
in a separate line to stdout.
I came up the code below.
I could not get sscanf to work because it does not increment its
position
on conversion (like scanf does). Is there some workaround for it ?
Please criticize the code below: I have a feeling I am missing a simple
and elegant solution, since the problem is so simple itself.
Moreover, there is a *bug* in the code: what happens when I have a 0 as
a number ?
Reading will stop then. How do I get around that ?
Are my malloc() error statements correct ? In general, is it not better
to state in
the malloc error's before exiting which variables failed to get
malloc'ed ?
#include <stdio.h>
#define MAX 80
int main() {
int i, n;
char *line, **errline, *lineA, *lineB;
line=malloc(MAX*sizeof(char));
errline=malloc(sizeof(*errline));
if ((line == NULL) || (errline==NULL)) {
fprintf(stderr, "Could not allocate memory");
exit(-1);
}
while (fgets(line,MAX, stdin)!=NULL) {
lineA=line;
while ((n=(int)strtol(lineA, errline, 0))!=0) {
printf("%d \n", n);
lineA=*errline;
// printf("Line is now at %s \n",lineA);
}
}
}