Reputation: 822
I'm trying to read lines and extract information from it. My text has for example;
abate terminar, hacer cesar
abated amainado, amplacado, mitigado
which is a dictionary. First word is english and rest are Spanish. I'm trying to save the english word into one variable and then the rest of the line into another one variable. I have no idea how to do that? I wrote this code that reads all the text file and prints it all.
int main(int argc, const char * argv[]) {
char filename[] = "/Users/MyName/Desktop/span.rtf";
FILE *file = fopen ( filename, "r" );
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
fprintf(stdout,"%s",line); }
fclose(file);
}
return 0;
}
Upvotes: 0
Views: 51
Reputation: 27231
Try this:
char english[256];
char spanish[256];
while(fscanf(file,"%[a-z]%*[ ]%[a-z, ]\n", english, spanish) != 0) {
fprintf(stdout, "English: %s\n Spanish: %s\n", english, spanish);
}
Upvotes: 0
Reputation: 399949
That's a great start, using fgets()
to read in whole lines which can then be parsed is a good approach in general.
Next you need to think about how to store your dictionary. One way might be a statically sized array of structures:
struct {
char *english;
char *spanish;
} words[1000];
This assumes no more than 1000 words.
To store each line, just find the first space character and let that be the split between English and Spanish:
size_t word_count = 0;
while(fgets(line, sizeof line, file) != NULL)
{
char * const sp = strchr(line, ' ');
if(sp != NULL)
{
*sp = '\0';
while(isspace((unsigned char) *++sp))
;
if(isalpha((unsigned char) *sp)
{
words[word_count].english = strdup(line);
words[word_count++].spanish = strdup(sp);
}
}
}
Something like that should get you started. This assumes the existance of strdup()
, if you don't have that re-implementing it is trivial. Of course you should add code to check for memory allocation failures.
Upvotes: 1