Reading in data from Text file

This is a discussion on Reading in data from Text file within the C Programming forums, part of the General Programming Boards category; so now when you have all the text read use something like strtol to convert chart1[i][j] into chart2[i-1][j-1] Code: for(i=1;i<11;i++) ...

  1. #91
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    so now when you have all the text read
    use something like strtol to convert chart1[i][j] into chart2[i-1][j-1]
    Code:
    for(i=1;i<11;i++)
       for(j=1;j<11;j++)
    where chart2 is declared as
    long chart2[10][10];
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  2. #92
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    Quote Originally Posted by vart View Post
    so now when you have all the text read
    use something like strtol to convert chart1[i][j] into chart2[i-1][j-1]
    Code:
    for(i=1;i<11;i++)
       for(j=1;j<11;j++)
    where chart2 is declared as
    long chart2[10][10];
    im confussed lol my chart i work with is a int chart and i dont know anything about strtol

  3. #93
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    This might just be confusing, but one alternative to this
    Code:
                 if( strcmp( pos[i], "London" ) == 0 ){point[i]=0;}
                 else if( strcmp( pos[i], "Bath" ) == 0 ){point[i]=1;}
                 /* ... */
                 else{printf("\n Invalid place please Re enter: ");i--;}
    is this:
    Code:
    const char *cities[] = {
        "London", "Bath", /* ... */
    };
    size_t x;
    
    for(x = 0; x < sizeof(cities) / sizeof(*cities); x ++) {
        if(!strcmp(cities[x], pos[i])) {
            point[i] = x;
        }
    }
    Of course, since the cities are in alphabetical order, you could do a binary search on them, but let's not get into that . . . . Wrapping that into a function would be a good idea, too.

    I'm not sure how much your code has changed, but post #85's code has an error here:
    Code:
    chart[stops[1]][stops[2] +
    (A missing ].)
    Code:
    if (choice < 1 | choice > 4)
    ->
    Code:
    if (choice < 1 || choice > 4)
    Code:
    scanf("%s", &pos[i]);
    ->
    Code:
    scanf("%s", pos[i]);
    A return 0; wouldn't hurt, either.

    Then it seems to be working for me . . . .
    Code:
     Please enter your Start point: London
    
     Please enter your Finishing point: Truro
    
     Please Enter the number of stops 0-3: 3
    
     Please enter the name for Stop 1: Durham
    
     Please enter the name for Stop 2: Leeds
    
     Please enter the name for Stop 3: York
    
     Starting from London To Durham is 456 miles
     From Durham To Leeds is 46 miles
     From Leeds To York is 19 miles
     From York To Truro is 78 miles
     Total Distance : 599
    Of course, that's with the static array chart.

    Now, how to convert chart1[] into chart[]? One way, if you don't like strtol(), is to use sscanf(). Has this been mentioned already? I haven't read the whole thread . . . .

    And you'll also have to load chart1[] from a file. I suggest fopen(), fgets(), strtok(), and fclose().

    Or combine the two steps and use fopen(), fscanf(), and fclose(). It's less robust, but easier.

    For example:
    Code:
    int x, y;
    
    for(y = 0; y < 10; y ++) {
        fscanf(fp, "%s", cityname[y]);
    }
    
    for(y = 0; y < 10; y ++) {
        fscanf(fp, "%s", unusedname);
        for(x = 0; x < 10; x ++) {
            fscanf(fp, "%i", &chart[y][x]);
        }
    }
    Something like that might get you started . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #94
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    lol im still conussed on what this code u throw at me is ment to do

    how ever i have fixed the problems its just getting that bloddy array into an int array
    Last edited by fortune2k; 03-22-2008 at 05:48 AM.

  5. #95
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include <errno.h>
    
    #define CITIES 10
    
    /* Structure holding the name and the distance. */
    
    typedef struct _Distance
    {
    	char *CityTo;
    	int dist;
    }Distance;
    
    /* Structure holding the name of the city and the distances from all other cities. */
    
    typedef struct _CityDistance
    {
    	char *CityFrom;
    	Distance *Cities;
    }CityDistance;
    
    /* Read the contents from the file. */
    
    CityDistance *ReadContents(const char *filename)
    {
    	if(!filename)
    	{
    		fprintf(stderr, "Error NULL filename pointer.\n");
    		return NULL;
    	}
    	else
    	{
    		/* Pointer to a file. */
    		FILE *fileptr = NULL;
    		/* Pointer to a CityDistance struct. */
    		CityDistance *CDist = NULL;
    		/* Index to Cities. */
    		static int Index = 0;
    		/* Iteration. */
    		int FirstIteration = 0;
    		int nError = 0;
    		/* Avoid Write. */
    		int AvoidWriteIndex = 0;
    		/* City Index. */
    		int CityIndex = 0, CityIndex1 = 0;
    		/* Buffer to hold the line. */
    		char LineBuffer[BUFSIZ] = "";
    		/* Pointer for strtok. */
    		char *token = NULL;
    		/* Try to open the file first. */
    		if((fileptr = fopen(filename, "rt")) == NULL)
    		{
    			fprintf(stderr, "Error in opening <&#37;s> filename.\n", filename);
    			return NULL;
    		}
    		/* Try to alloc memory. */
    		if((CDist = calloc(CITIES, sizeof(CityDistance))) == NULL)
    		{
    			fprintf(stderr, "Error in memory.\n");
    			fclose(fileptr);
    			return NULL;
    		}
    		for(Index = 0; Index < CITIES; Index++)
    		{
    			if((CDist[Index].Cities = calloc(CITIES-1, sizeof(Distance))) == NULL)
    				for(; Index >= 0; Index--)
    				{
    					free(CDist[Index].Cities);
    					CDist[Index].Cities = NULL;
    				}
    		}
    		if(!Index)
    		{
    			free(CDist); CDist = NULL;
    			fclose(fileptr);
    			return NULL;
    		}
    		/* Set Index Back to zero. */
    		Index = 0;
    		/* Read from file. */
    		while((fgets(LineBuffer, sizeof(LineBuffer), fileptr)) != NULL && Index < CITIES)
    		{
    			/* Trim the pending '\n' in the end due to fgets(). */
    			if(LineBuffer[strlen(LineBuffer)-1] == '\n')
    				LineBuffer[strlen(LineBuffer)-1] = '\0';
    			/* Did we read something. */
    			if(LineBuffer[0] == '\0')
    				break;
    			/* Use strtok. */
    			token = strtok(LineBuffer, " ");
    			if(!FirstIteration && token)
    			{
    				while(token != NULL && Index < CITIES)
    				{
    					CDist[Index++].CityFrom = strdup(token);
    					token = strtok(NULL, " ");
    				}
    				/* Init CitiesTo. */
    				for(Index = 0; Index < CITIES; Index++)
    				{
    					while(CityIndex < CITIES)
    					{
    						if(CityIndex != Index)
    							CDist[Index].Cities[CityIndex1++].CityTo = strdup(CDist[CityIndex].CityFrom);
    						CityIndex++;
    					}
    					CityIndex1 = 0;
    					CityIndex = 0;
    				}
    				/* Reset Counters. */
    				Index = 0, CityIndex = 0;
    				/* Ensure we will not enter. */
    				FirstIteration = 1;
    			}
    			if(FirstIteration && token && nError)
    			{
    				while(token != NULL)
    				{
    					if(!strcmp(token, "-") || !strcmp(token, CDist[Index].CityFrom))
    					{
    						token = strtok(NULL, " ");
    						continue;
    					}
    					CDist[Index].Cities[CityIndex++].dist = atoi(token);
    					token = strtok(NULL, " ");
    				}
    			}
    
    			/* In any case. */
    			if(nError)
    				Index++;
    			nError = 1;
    			CityIndex = 0;
    			memset(LineBuffer, 0 , sizeof(LineBuffer));
    		}
                            fclose(fileptr);
    		return CDist;
    	}
    }
    /* Print the results. */
    
    void PrintCitiesAndDistances(const CityDistance *cities)
    {
    	int CityIndex = 0, DistanceIndex = 0;
    	for(CityIndex = 0; CityIndex < CITIES; CityIndex++)
    	{
    		printf("\nPrinting Distances from:%s\n\n", cities[CityIndex].CityFrom);
    		while(DistanceIndex < CITIES-1)
    		{
    				printf("From:%s---->To:%s = %d\n", cities[CityIndex].CityFrom, cities[CityIndex].Cities[DistanceIndex].CityTo, cities[CityIndex].Cities[DistanceIndex].dist);
    				DistanceIndex++;
    		}
    		DistanceIndex = 0;
    	}
    	printf("\n\n");
    }
    
    /* Main Code. */
    int main(int argc, char *argv[])
    {
    	int i;
    	CityDistance *n = NULL;
    	n = ReadContents("cities.txt");
    	PrintCitiesAndDistances(n);
    	printf("Hit enter to continue...");
    	getchar();
    }

    Bokarinho....
    Last edited by Bokarinho; 03-23-2008 at 04:03 AM. Reason: WTF?

  6. #96
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,667
    It's really excellent that you have his homework so well planned out, Bokarinho. You should be getting paid for this.

    A much more elegant solution exists using parallel arrays, by the way.
    Last edited by whiteflags; 03-22-2008 at 08:12 PM.

  7. #97
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    it doesnt help geeting taught the very basics very badly and well alot of code u guys give me confusses me haha but i shall give it a shot

  8. #98
    Registered User
    Join Date
    Mar 2008
    Posts
    7
    I have the same Assignment,
    im stuck at the point where we have to read in a .txt file of numbers and put them into a 2d array.

    The code im using for opening the file, and putting the numbers into a 2d array is:
    Code:
     FILE *file;
     int a = 0, b = 0;
     int table[a][b];
     file = fopen("numbers2.txt", "r");
    Code:
    if(file != NULL) // file exists
      {
        
        printf("File opened successfully.\n");
          
           for (a=0; a <= col;a++)
            {
              for (b=0; b <= row;b++)
               {
               fscanf(file, "&#37;d ", &table[a][b]);
                
    
                printf("%-4d ", table[a][b]);
               }
               printf("\n");
             }
           
          fclose(file);                  
      }
        else // file doesn't exist
     {
      printf("Error: can't open file\n");
     }
    in my program I have a switch statement for the different options, 1 of the options is to display the numbers:

    Code:
    File opened successfully.
    0    23   12   89   456  123  46   732  345  123
    23   0    46   234  123  46   89   234  567  90
    12   46   0    767  456  46   234  123  732  35
    89   234  767  0    732  32   48   67   98   100
    456  123  456  732  0    234  46   89   89   732
    123  46   46   32   234  0    123  46   123  234
    46   89   234  48   46   123  0    46   89   19
    732  234  123  67   89   46   46   0    123  732
    345  567  732  98   89   123  89   123  0    78
    123  90   35   100  732  234  19   732  78   0
    Then the first option in the program is to enter 2 numbers,

    printf("Enter 2 Numbers: ");
    Distance = (table[num1][num2]);
    printf("%-4d", table[num1][num2]);
    printf(" Miles");
    printf("\n");
    So it should be reading from the 2d array, the problem is that it seems to be only reading the very bottom row and doesn't read the columns at all:

    Code:
    ------------------------------
    Please enter your choice:
    ------------------------------
    1
    Enter 2 Numbers: 2
    2
    35   Miles
    
    ------------------------------
    So I think that it isn't actually inserting the numbers in the txt file into a 2d array?
    Any help would be appreciated.

  9. #99
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    printf("Enter 2 Numbers: ");
    Distance = (table[num1][num2]);

    Shouldn't you have some input between these two lines?
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  10. #100
    Registered User
    Join Date
    Mar 2008
    Posts
    7
    So at the moment it's just reading 1 of the numbers input? or assigning the same number to both num1 and num2?. How do I fix this?

  11. #101
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    at the moment it is using the same values of the num1,num2 vars that are left from the previous calculations.

    if you asking to enter 2 numbers use some input function to read them - for example scanf
    Code:
    if(scanf("&#37;d%d", &num1, &num2) == 2)
    {
       /* use the input */
    }
    else
    {
       /* clear the stdin and try again */
    }
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  12. #102
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    So at the moment it's just reading 1 of the numbers input? or assigning the same number to both num1 and num2?. How do I fix this?
    By using scanf() or some such. What you have now never looks at what the user enters. You need something like this:
    Code:
    printf("Enter 2 Numbers: ");
    scanf("&#37;d%d", &num1, &num2);
    Distance = (table[num1][num2]);
    (Once you understand that, check vart's more robust example.)
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  13. #103
    Registered User
    Join Date
    Mar 2008
    Posts
    7
    Quote Originally Posted by dwks View Post
    By using scanf() or some such. What you have now never looks at what the user enters. You need something like this:
    Code:
    printf("Enter 2 Numbers: ");
    scanf("%d%d", &num1, &num2);
    Distance = (table[num1][num2]);
    (Once you understand that, check vart's more robust example.)
    Ok, I tried this, and it prints this:

    ------------------------------
    Please enter your choice:
    ------------------------------
    1
    Enter 2 Numbers: 3
    3
    4199093 Miles

    ------------------------------
    I don't know where it's getting that number from :s

  14. #104
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    so try to extend your printf

    Code:
    printf("[&#37;d][%d] = %-4d", num1, num2, table[num1][num2]);
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  15. #105
    Registered User
    Join Date
    Mar 2008
    Posts
    7
    OK done that:

    ------------------------------
    Please enter your choice:
    ------------------------------
    1
    Enter 2 Numbers: 6
    5
    [6][5] = 2009252579 Miles

    ------------------------------
    I don't know where it's getting the 2009252579 number from :s
    I guess it's not putting the numbers from the txt file into a 2d array correctly.

    It should return 234 Miles.

    This is the code I have for opening the txt file, scanning it and putting it into an array:

    Code:
    if(file != NULL) // file exists
      {
        
        printf("File opened successfully.\n");
          
           for (a=0; a <= col;a++)
            {
              for (b=0; b <= row;b++)
               {
               fscanf(file, "%d ", &table[a][b]);
                
    
                printf("%-4d ", table[a][b]);
               }
               printf("\n");
             }
           
          fclose(file);                  
      }
        else // file doesn't exist
     {
    It should be putting the numbers from the txt file into a 2d Array, I guess it's not?, and if it's not, hope do I get it to work correctly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading data from a text file
    By Dark_Phoenix in forum C++ Programming
    Replies: 8
    Last Post: 06-30-2008, 02:30 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. reading from text file
    By jamez in forum C Programming
    Replies: 3
    Last Post: 11-30-2005, 06:13 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 02:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21