Click to See Complete Forum and Search --> : parsing a file
shaggy112
12-01-2001, 11:32 AM
Hello
I am trying to parse a file and only get the first string on the line. I am simply using fstream, and will put the strings into an array. The only problem that I am having is how do i grab the first string, then move to the next line? Here is an example:
-----file to parse----
ABC DEF 123
DEF 345
XYZ JTR 543
----end-----
I need to get just the first string
-----output from above------
ABC
DEF
XYZ
---end----
thanks for any help
Fimbulvetr
12-01-2001, 12:01 PM
Might be a dumb question but what are ya using? (PHP, Perl, C++,)?
Strogian
12-01-2001, 12:36 PM
Not a dumb question at all. It would also help to post your program up here.
Fimbulvetr
12-01-2001, 12:45 PM
Well after a little deduction, I found that this maybe a good place to check out:
http://gethelp.devx.com/techtips/cpp_pro/10min/2001/june/10min0601.asp
Strike
12-01-2001, 04:21 PM
If you are using C (though fstream is C++), you can just use fscanf like so:
char my_string[255];
FILE *my_file;
my_file = fopen("/some/path", "r");
fscanf(my_file, "%s %s %s", my_string, NULL, NULL);
I don't really remember the C++ way of doing it as I haven't done C++ file I/O in a while. I think it is something like this:
fstream my_file("/some/path");
string buffer;
getline(my_file, buffer);
Of course, I can't think of the "typical" way you would get the first string out of that buffer before you hit whitespace.
debiandude
12-01-2001, 05:19 PM
I don't think you can use fscanf because each line doesnot have the same ammount of elements. Here is something I threw together using some code I had lying around.
#include <stdio.h>
#include <string.h>
#define MAXELEMENTS 10
char **split(char *delim, char *str);
int main(void) {
FILE *fp;
char buf[1024], **list;
if((fp = fopen("filename", "r")) == NULL) {
perror("ERROR: Can't open file");
exit(1);
}
while(!feof(fp)) {
if(fgets(buf, 1024, fp)) {
list = split(" ", buf);
printf("%s\n", *list);
}
}
return 0;
}
char **split(char *delim, char *str) {
char *token;
static char *list[MAXELEMENTS];
int i = 0;
token = strtok(str, delim);
list[i++] = token;
while(((token=strtok(NULL, delim)) != NULL) && (i<MAXELEMENTS)) {
list[i++] = token;
}
return(list);
}
Stuka
12-01-2001, 06:20 PM
Try this://fstream for file input already assumed
string str;
getline(infile, str); //str now contains entire first line
str.substr(0, str.find(' ') + 1); //Gets up to the first space