strtok but only want the last field

V

vijay

I have a file with lines like

1|22|333
4444|55555|666666
ccc|bb|a

I only need the last field. What I am doing now is using strtok to
split the lines and ignoring the first two fields. Can someone suggest
a better way to do this?
 
D

dj3vande

I have a file with lines like

1|22|333
4444|55555|666666
ccc|bb|a

I only need the last field. What I am doing now is using strtok to
split the lines and ignoring the first two fields. Can someone suggest
a better way to do this?

strrchr?

Depending on what you need them for, unix shell tools like sed or cut
might also be useful, and if they are they'd save you the trouble of
writing (much) code.


dave
(you could even go to The Dark Side and use Perl)
 
J

Jack Klein

I have a file with lines like

1|22|333
4444|55555|666666
ccc|bb|a

I only need the last field. What I am doing now is using strtok to
split the lines and ignoring the first two fields. Can someone suggest
a better way to do this?

Can you define what you mean by "better"? What's wrong with using
strtok(), assuming you use it correctly?

If it were me, I'd use strchr() four times, the last three starting at
the address returned by the previous call + 1. I would verify that
the first three all returned non-null pointers, and that the last one
returned a null pointer. That way I could recognize and reject
invalid input, and still have the string I read intact to output in an
error message.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
 
W

William Ahern

vijay said:
I have a file with lines like

I only need the last field. What I am doing now is using strtok to
split the lines and ignoring the first two fields. Can someone suggest
a better way to do this?

#include <stdio.h> /* getchar(3) ferror(3) */
#include <stdlib.h> /* abort(3) */

#define MAXFIELDWIDTH 64

int main(void) {
char field[MAXFIELDWIDTH];
size_t p = 0;
int ch;

while (EOF != (ch = getchar())) {
switch (ch) {
case '\n':
printf("%.*s\n", (int)p, field);

/* FALL THROUGH */
case '|':
p = 0;

break;
default:
if (p >= sizeof field)
abort();

field[p++] = ch;
} /* switch() */
} /* while (!EOF) */

if (ferror(stdin))
abort();

return 0;
} /* main() */
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,438
Messages
2,571,699
Members
48,796
Latest member
Greg L.
Top