I'm new at using these things, so I'm getting stuck writing a program.
I have to write a program that outputs the n'th token in a line. The
program is called nth, so if I type in "nth 3" then the program gets
input from stdin (the keyboard). If I type "hello there, robert" as
input, then the program will output the third token, "robert", and
wait for me to enter another line. It will keep doing this, waiting
for me to type lines, then giving me the n'th token of that line,
until I type control-D. Lines in this program can be as long as 500
characters.
Also, I can have more than one argument. The first argument is
obviously n, the number of the token I want, but any subsequent
arguments are files containing input to be processed as above. If I
call "nth 3 input.txt" and input.txt is a file containing the line
"hello, there robert", then the output will be the same as the first
example where I typed the line in manually. I should be able to put as
many file names as I like for arguments and they'll be processed
sequentially. So "nth 3 input.txt input.txt" would output:
robert
robert
If the n'th token doesn't exist, for example I type "nth 10 input.txt"
then a newline is printed.
With my very limited knowledge of C, I've got this sort of working,
but can't fix my bugs. I've got it partially working in the case where
it reads input from stdin. It does what it is supposed to do, except
exit when I type control-D.
I think I need some test to see if the character entered is EOF, but I
can't find where to put it.
And in the case where the program gets input from a file, I can only
get the program to read and give the n'th token of the{*filter*}line. If I
have an input2.txt that looks like this:
Hello there, what's up?
How are you
I'm ok thanks
Then "nth 2 input2.txt" should output:
there
are
ok
"nth 4 input2.txt" would output the token "up?" then two newlines.
I can only get the program to output the first line, "there". I know I
need a loop somewhere, but every loop I try just goes on infinitely.
Here's my code. Thank you to anyone who can tell me where I'm going
wrong!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* process - helper function which prints the nth line of a given
* file, f.
*/
void process(FILE *f, int n_value) {
char *p;
char buf[500];
int i;
fgets(buf, sizeof buf, f);
p = strtok(buf, " \n\t");
for (i = 1; i < n_value; i++) {
p = strtok((char *)NULL, " \n\t");
}
if (p == NULL) {
printf("\n");
} else {
printf("%s\n", p);
}
Quote:
}
int main(int argc, char **argv) {
int i;
int nth_element = atoi(argv[1]);
while (argc == 2) {
process(stdin, nth_element);
}
if (argc > 2) {
FILE *fp;
for (i = 2; i < argc; i++) {
if ((fp = fopen(argv[i], "r")) == NULL) {
perror(argv[i]);
return(0);
}
process(fp, nth_element);
fclose(fp);
}
}
return(0);
Quote:
}