0

I am trying to get the address of a certain line in a text file. This line contains the following;

Kmart, 7055 East Broadway, Tucson AZ

I am using strcpy and strtok functions to extract the address (7055 East Broadway), but so far I've only been able to extract the name of the store (Kmart) using my code.

char strLine[] gets the line from the file and I would like to return it to char strAddress[]

How would I extract just the address and possibly the city and state?

#define MAX_CHARS_PER_LINE 80

void getAddress(char strAddress[], const char strLine[])
{

   char newLine[MAX_CHARS_PER_LINE+1];

   strcpy(newLine,strLine);
   char* token = strtok(newLine, ",");

   strAddress = token;

   printf("%s\n",strAddress);


}
thn
  • 3
  • 3
  • [man strtok](https://linux.die.net/man/3/strtok), here you can find an example for using `strtok` – Shubham Jul 11 '19 at 06:16

1 Answers1

0

Assuming,

  1. The address is the second element in the line
  2. It is demarcated with commas.

You can use strtok to get the address as below.

void getAddress(char strAddress[], const char strLine[])
{
   char newLine[MAX_CHARS_PER_LINE+1];

   strcpy(newLine,strLine);

   char* token = strtok(newLine, ",");
   if (token != NULL)
   {
        token = strtok(NULL, ",");
   }
   if (token != NULL)
   {           
       strcpy (strAddress,token);
   }            
   return; 
}   

To get the city and state just call token = strtok(NULL, ","); one more time

What if I wanted to separate the city-state and just get the city and get the state separately?

This is a more complex job as you do not have a comma in between the city and the state. You also need to take care of the case where the city can have two words e.g. New Orleans.

You can possibly assume that the state has 2 characters. In this case, a suggested route is

  1. Isolate City + State in a string
  2. Remove spaces at the end of the string
  3. The last 2 characters of the string are the state.
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • You should also point out that `strAddress` should point to valid and enough memory. – kiran Biradar Jul 11 '19 at 06:11
  • Yes, that should be taken care of by the calling function. – Rishikesh Raje Jul 11 '19 at 06:15
  • And `token` should be tested for `NULL` each time. – the busybee Jul 11 '19 at 06:28
  • Thank you! How would I account for the the cities having a space in between them? I can isolate a string with the city and state but separating them is my issue – thn Jul 11 '19 at 06:56
  • It is generally not possible to separate in this case. You need to find some other factor that you can use that is constant throughout your dataset. I have suggested an alternative with assuming that the last 2 characters are the state. – Rishikesh Raje Jul 11 '19 at 07:16