Thread: copying a string to an array

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    14

    copying a string to an array

    hey, this is my problem/homework. A user inputs a city and state and the program searches a text file for the name. The latitude and longitude is given in the text file and the distance is calculated.

    The stuff in the txt file are in this format: " [Los_Angeles/CA:city] 34.08616 -118.37598 "

    I have to make 3 arrays (for city, latitude, and longitude). My problem is that I can't get the array to read the city. Here is my code:





    Code:
    #include<iostream>
    #include<fstream>
    #include<iomanip>
    #include<cstdlib>				//includes libraries
    #include<string>
    
    using namespace std;
    
    const int SIZE= 25374;
    
    
    string name[SIZE];
    double latitude[SIZE];
    double longitude[SIZE];
    
    int main()
    {
    	ifstream inStream;
    	
    	inStream.open("US-PLACES.txt");
    
    	for(int i=0;i<=25374;i++){
    		inStream>>name[i];
    		cout<<i<<endl;
    	}
    cout<<"hey";
    	for(int j=0;j<25374;j++){
    		cout<<name[i];
    	}
    cout<<"hey";	
    	return(0);
    
    
    
    }

  2. #2
    Registered User
    Join Date
    Mar 2003
    Posts
    4
    Hi, firstly why are the arrays so large? if the input is in the format given, 22 is enough for the name which includes one extra character for the null.

    Try something like this . . .
    Code:
    instream >> name;         // read ahead
    
    while(!instream.eof())
    {
       instream >> latitude >> longitude;
       functionToCheckForNameHere();   //check for name & process
       instream >> name;
    }
    PS Don't forget to close the file. Hope this helps

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    14
    The array is that large because that is the number of cities in the txt file. Wouldn't one array slot suffice for each city?

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Version 1:
    1) read data from file line by line storing each line as a string using getline() with newline char as delimiter.
    2) parse each line into three strings using your own parsing function, strok(), or find() depending on what type of string you are planning to use.
    3) change the last two strings into type double using atof() or toInt() method of appropriate string class.

    Version 2:
    1) read data from file char by char creating strings as you go along
    2) change the last two strings into type double using atof() as in Version 1.

    Version 3:
    1) read first item into string using space as delimiter of get() or getline().
    2) read second and third items into type double directly.

    Version 4:
    1) Use one of the above options but leave all three data fields as strings, without converting the latter to type double.

    In each case you need to decide how to handle the [] surrounding the cities name--keep them or dump them somehow. Also keep or dump the underscore between the separate parts of a name

    Since you started out using the char by char read in you can continue that approach if you wish. It is probably the easiest way to handle []_ issues.

    When declaring an instance of the STL string class you do not declare the size of the string as do with C style string using the [] after the objects name. Just use the type and object name.

    string myString;

    I'm not sure if the STL string class allows you to indicate the initial length of a string. If so, it is probably similar to the method used in other STL classes like so:

    string myString(2387);

    The reference I have doesn't indicate that a constructor using a single int as as an argument exists, however.

    You can use the [] operator to access a random element in an STL string, as you do. But, remember, that the STL string class is built upon an embedded char array used as a C style string (and accessable by the c_str() method) so be sure to add a terminating null character at the end of the input used to create a string.

    You lose the power of either a C style string or and STL string by using char by char output. If you terminate the char input with a null terminating char you can output the entire char array as the string itself, not a sequence of individual characters.

    there may be 25374 cities in the file, but you don't need 25374 char to make up the cities name, the longitute or the latitude. If you want to create a table with all the names so you can sort it or search it or whatever, then create a struct with three data members and then an array (or some other container here and everywhere I say array for the rest of this paragraph) of structs, OR use one array of strings for the city names, one array of doubles for the longitudes, and one array of doubles for the lattitudes, OR an array of strings where each string contains an entire line of the file, OR an array of an array of strings where the overall array contains the entire file, but each sub array contains the three strings containing the data for a given city.

    If you try to put the data for a given city as an entry in a container, then you either need to keep the latitude and longitude as strings and convert them when you want to use them for calculations OR use a struct/class to hold the data for each city as you can't mix datatypes in a given container OR use several different containers to hold the data and use the index for each entry as the key for accessing data in different containers.

  5. #5
    Registered User
    Join Date
    Jan 2003
    Posts
    14
    elad- thanks for your help.

    what is the correct syntax to read in from a file and put it into an array?

  6. #6
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    depends on the array and what you need to do:

    read file one char at a time into char array to create a single string from the whole file
    Code:
    char input*;
    input = new char[1000000];
    char ch;
    long index = 0;
    
    ifstream fin("filename.ext");
    
    if(!fin)
    {
      cout << "oops" << endl;
    }
    else
    {
      fin >> ch;
      while(!fin.eof())
      {
         input[index++] = ch;
      }
    }
    input[index] = '\0';
    read from file into a buffer one word at a time to create an array of C style strings:
    Code:
    char words[100][20];
    int index;
    ifstream fin("filename.ext");
    fin >> words[index++];
    while(!fin.eof() && index < 100)
    {
      fin >> words[index++];
    }
    read from file into a buffer one line at a time, where line is terminated by newline char and maximum 123 char per line
    Code:
    char lines[10][124];
    //do dah
    fin.getline(lines[index++], 124, '\n');
    while(!fin.eof() && index < 10)
    {
      fin.getline(lines[index++], 124);
    }
    create a vector of STL strings from file using ] as delimeter between strings
    Code:
    vector <string> lines;
    string buffer;
    
    getline(fin, buffer, ']');
    while(!fin.eof())
    {
       getline(fin, buffer, ']');
       lines.push_back(buffer);
    }
    the possibilities are endless, depending on your needs, desires, and attitudes.

  7. #7
    Registered User
    Join Date
    Jan 2003
    Posts
    14
    thanks again elad-

    i already got it to work before yor post though...sort of.

    I'm having trouble with my function that compares the inputted string (a city) to all the cities in the array. It is supposed to be a search function.

    Code:
    #include<iostream>
    #include<fstream>
    #include<iomanip>
    #include<cstdlib>				//includes libraries
    #include<string>
    
    using namespace std;
    
    const int SIZE= 25375;
    
    
    string city[SIZE];
    char letters[80];
    double latitude[SIZE];
    double longitude[SIZE];
    int saveMe[1000];
    int counter=0;
    
    
    void calculateDistance(double startingLatitude, double endingLatitude, double startingLongitude, 
    					  double endingLongitude, double dist, int j) 
    {
        
    	const double Pi= 3.14159265359;
    	double radiusEarth=3958.8, distance;
    		
    		
    	startingLatitude= ((startingLatitude)/180)*Pi;
    	endingLatitude= ((endingLatitude)/180)*Pi;
    	startingLongitude= ((startingLongitude1)/180)*Pi;
    	endingLongitude= ((endingLongitude1)/180)*Pi;
    
    	distance = cos(startingLatitude)*cos(endingLatitude)*cos(startingLongitude-endingLongitude);	
    	distance += (sin(startingLatitude)*sin(endingLatitude));
    	distance = acos(distance);
    	distance *= radiusEarth;
    	
        if(distance<=dist){
    		saveMe[counter]=j;
    		counter++;
    	}
    
    	
     } 
    
    
    int checkDistance(int position,double distance, int i)
    {
    	do{
    		if(i != position)	
    			calculateDistance(latitude[position], latitude[i], longitude[position], longitude[i], distance);
    		i++;
    	}while(i<25375);
    	
    	return0;
    }
    
    int search()
    {
    	string input;
    	int i= 0, pos=-1;
    
    	cin>>input;
    	
    	do{
    		if (input.find(city[i]) != -1){
    			cout<<city[i]<<endl;
    			if (pos != -1)
    				return -2;
    			pos = i;}
    			
    			i++;
    		
    		}while(i<25375);
    
    	cout<<"hello "<<pos<<endl;
    		return pos;
    
    	}
    
    
    int main()
    {
    	ifstream inStream;
    	
    	inStream.open("US-PLACES.txt");
    
    	int i= 0, pos;
    	string place;
    	double lat, longi, distanceLimit;
    
    	while(!inStream.fail())
    	{
    		inStream >> place >> lat >> longi;
    		city[i] = place;
    		latitude[i] = lat;
    		longitude[i] = longi;
    		i++;
    	
    	}
    
    
    	cout<<"Thank you for calling information. What city please?"<<endl;
    	
    	pos=search();
    	
    	if 	(pos == -2){
    		cout<<"Narrow your search down!!"<<endl;
    		return(-1);
    		}
    	
    	if  (pos == -1){
    		cout<<"Nothing found!!"<<endl;
    		return(-1);
    		} 
    
    cout<<endl<<pos<<endl;
    
    	cout<<"What is your distance limit"<<endl;
    	cin>>distanceLimit;
    	checkDistance(pos,distanceLimit);
    
    
    return(0);
    }
    the way i want the search function to work is that i want it to return -1 if no matches were found, return -2 if several matches were found, and return the position of the array if only one match was found. I appreciate your help.

  8. #8
    Registered User
    Join Date
    Jan 2003
    Posts
    14
    code that compiles might help!




    Code:
    #include<iostream>
    #include<fstream>
    #include<iomanip>
    #include<cstdlib>				//includes libraries
    #include<string>
    #include <cmath>
    
    using namespace std;
    
    const int SIZE= 25375;
    
    
    string city[SIZE];
    char letters[80];
    double latitude[SIZE];
    double longitude[SIZE];
    int saveMe[1000];
    int counter=0;
    
    
    void calculateDistance(double startingLatitude, double endingLatitude, double startingLongitude, 
    					  double endingLongitude, double dist, int j) 
    {
        
    	const double Pi= 3.14159265359;
    	double radiusEarth=3958.8, distance;
    		
    		
    	startingLatitude= ((startingLatitude)/180)*Pi;
    	endingLatitude= ((endingLatitude)/180)*Pi;
    	startingLongitude= ((startingLongitude)/180)*Pi;
    	endingLongitude= ((endingLongitude)/180)*Pi;
    
    	distance = cos(startingLatitude)*cos(endingLatitude)*cos(startingLongitude-endingLongitude);	
    	distance += (sin(startingLatitude)*sin(endingLatitude));
    	distance = acos(distance);
    	distance *= radiusEarth;
    	
        if(distance<=dist){
    		saveMe[counter]=j;
    		counter++;
    	}
    
    	
     } 
    
    
    int checkDistance(int position,double distance)
    {
    	int i =0;
    	
    	do{
    		if(i != position)	
    			calculateDistance(latitude[position], latitude[i], longitude[position], longitude[i], distance, i);
    		i++;
    	}while(i<25375);
    	
    	return 0;
    }
    
    int search()
    {
    	string input;
    	int i= 0, pos=-1;
    
    	cin>>input;
    	
    	do{
    		if (input.find(city[i]) != -1){
    			cout<<city[i]<<endl;
    			if (pos != -1)
    				return -2;
    			pos = i;}
    			
    			i++;
    		
    		}while(i<25375);
    
    	cout<<"hello "<<pos<<endl;
    		return pos;
    
    	}
    
    
    int main()
    {
    	ifstream inStream;
    	
    	inStream.open("US-PLACES.txt");
    
    	int i= 0, pos;
    	string place;
    	double lat, longi, distanceLimit;
    
    	while(!inStream.fail())
    	{
    		inStream >> place >> lat >> longi;
    		city[i] = place;
    		latitude[i] = lat;
    		longitude[i] = longi;
    		i++;
    	
    	}
    
    
    	cout<<"Thank you for calling information. What city please?"<<endl;
    	
    	pos=search();
    	
    	if 	(pos == -2){
    		cout<<"Narrow your search down!!"<<endl;
    		return(-1);
    		}
    	
    	if  (pos == -1){
    		cout<<"Nothing found!!"<<endl;
    		return(-1);
    		} 
    
    cout<<endl<<pos<<endl;
    
    	cout<<"What is your distance limit"<<endl;
    	cin>>distanceLimit;
    	checkDistance(pos,distanceLimit);
    
    
    return(0);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying a string, into a string array.
    By m.mixon in forum C Programming
    Replies: 5
    Last Post: 07-31-2006, 05:19 PM
  2. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  3. can't assign proper values to an array of string
    By Duo in forum C Programming
    Replies: 1
    Last Post: 04-04-2005, 06:30 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM