user2158031
user2158031

Reputation: 81

Reading in a full line from .txt file and storing specific information into different strings

So my .txt file looks like this:

Firstname MiddleName Lastname
Streetnumber streetname city state zipcode

I can use fgets() to read in each line easily; however I need to store each bit of information into its own char array.

Using fscanf("%s%s%s", %(ptr->name.firstname), %(ptr->name.middlename, %(ptr->name.lastname))

I can easily do this. However the problem I run into is when the information has a space in between. For example of someone entered the address info:

1223 West Minster London CA 12332

Using fscanf(fp, "%s%s%s%s%s", &(ptr->streetno), &(ptr->streetname), &(ptr->city), &(ptr->state), &(ptr->zip)

The stored values would be:

streetno: 1222, streetname: West, city: Minster, state: London, zip: CA. 

streetname needs to be 'West Minster' but fscanf("%s") reads till a whitespace.

Upvotes: 0

Views: 101

Answers (1)

Gene
Gene

Reputation: 46960

If the all words are separated by spaces, then the address alone is not enough information. Consider

123 Biddle Lane Fort Lauderdale FL 33301

How can a "dumb" algorithm know where the division between street and city occurs? It can't.

But all is not lost. If all addresses are US, you have a way forward. You can obtain a free database that allows mapping zip codes to city names. This can solve the ambiguity problem in many cases. The algorithm would be something like:

  1. Separate the line into words. Say there are N of them.
  2. Assume the last is zip code.
  3. Look up the zip in database to obtain a state and primary city.
  4. Verify N-1'th word is state that matches zip.
  5. If primary city from database has M words, assume words N-3-M to N-2 are the city name.
  6. Assume the words preceeding the city name are the street address.

Upvotes: 2

Related Questions