Thread: Reading in data from Text file

  1. #31
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by Elysia View Post
    It my turn to be confused now. What are you talking about?
    I'm saying that it's a standards-compliant compiler that require you to write code in standards compliant way so that it will compile without modifications on other compilers.
    This is unlike MSVC6, whose standards compliance was very poor. Code written for that compiler did not compile in other compilers or vice versa.
    Mm'kay, that's what I thought you meant. It was very confusing, however. Read your previous responses and you might see what I mean . . . .

    Not really a compiler writer... such things are beyond my current experience.
    And what would the compiler be written in? C?
    Yes; well, mostly C, with some inline assembler thrown in. It probably also uses bison/yacc, though I've never checked. (It used to, I know that.)

    Code::Blocks is a nice GUI, I can see. I like it.
    Of course, it depends on the GCC compiler, and that's bad.
    No -- you can use any number of compilers with Code::Blocks, including the MSVC compiler. You might want to have a look at that, eh? Nice warnings, nice GUI!
    http://wiki.codeblocks.org/index.php...orted_compiler
    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.

  2. #32
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    That's not all, of course. It needs to have powerful debugging facilities, IntelliSense support (Visual Assist X?) and the ability to specify compile options within the GUI and not via the command line.
    Many of these things aren't listed (and Microsoft's debugging facilities are only partially supported from what I gathered), so it isn't that easy to come by information.

    And no thanks to writing a compiler, if it's written in C. C is stupid IMHO.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #33
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    Quote Originally Posted by Elysia View Post
    You understand that strings are basically an array with chars, with the last element in the array being '\0', right? The '\0' means "this is the end of the string." So we can abuse that to "truncate" the string. By doing that, all functions will think the string ends there, so we can easily copy just a part of the string using strcpy.
    We can also use pointers to specify a start. Since a pointer can point anywhere in memory, we can just set it to a position within the string. When you pass that pointer to functions, they'll think the string starts where that pointer points (inside the string). Makes sense?
    Therefore, we can do something like this:

    Code:
    char mystr[] = "This is my test string";
    char temp[50];
    char* p = NULL;
    while ( p = strstr(mystr, " ") ) /* Find the first space */
    {
    	*p = '\0'; /* Truncate the string */
    	strcpy(temp, mystr); /* Copy part of word to new buffer */
    	printf("%s ", temp); /* Print temporary buffer plus a space */
    	p++; /* Advance the position in the string to the next character */
    	/* Rinse and repeat! */
    }
    This is a simple example.

    ive been doin some reading on strings and will i require \0 after each element say for instance in my text file i had Ted Fred i want each name in a sepreate location in an array would i have to put the \0 sooo like Ted\0 Fred\0 sooo the each element can be recognised

    right i have figured out how i want my program set out im currently in the proccess of editing the following
    Code:
    #include "stdio.h"
    #include "string.h"
    struct entry
    {
    char name[21];
    int age;
    };
    void read_table(struct entry [], int);
    void print_table(struct entry [], int);
    int main(void)
    {
    struct entry list[1000];
    // max of 1000 entries
    int n=11;
    read_table(list, n);
    print_table(list, n);
    return 0;
    }
    void read_table(struct entry table[], int n)
    {
    int i;
    char line[81], filename[21];
    FILE *infile;
    filename = 'data.txt';
    infile = fopen(filename, "r");
    for (i=0; i<n; i++)
    {
    fgets(line, 80, infile);
    sscanf(line, "%s%d", table[i].name, &table[i].age);
    // name is a string, ie already an address!
    }
    fclose(infile);
    }
    void print_table(struct entry list[], int n)
    {
    int i;
    FILE *outfile;
    char filename[21];
    printf("\ntype OUTPUT FILE NAME %s", filename);
    scanf("%s", filename);
    outfile = fopen(filename, "w");
    if (outfile == NULL)
    {
    printf("\ncannot open output file %s\n", filename);
    exit (1);
    }
    for (i=0; i<n; i++)
    fprintf(outfile, "%s\t%d\n", list[i].name, list[i].age);
    fclose(outfile);
    }
    i understand the program above does completly differnt things it was a simple program i made yesterday im trying to strip it down and adapt it to do what im after

    i want the read method to read in all the data from the text file and store it in an array and also prepare it so it can be used to do calculations with.. the print mehtod will print out the grid on screen .. soo what you guys think it needs Mayjor editing but what you think for a start and i am a newb at this
    thankyou
    Last edited by fortune2k; 03-05-2008 at 07:08 PM.

  4. #34
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    For starters, read http://cboard.cprogramming.com/showp...37&postcount=9
    And please indent your code next time:
    Code:
    #include "stdio.h"
    #include "string.h"
    struct entry
    {
    	char name[21];
    	int age;
    };
    void read_table(struct entry [], int);
    void print_table(struct entry [], int);
    int main(void)
    {
    	struct entry list[1000];
    	// max of 1000 entries
    	int n=11;
    	read_table(list, n);
    	print_table(list, n);
    	return 0;
    }
    void read_table(struct entry table[], int n)
    {
    	int i;
    	char line[81], filename[21];
    	FILE *infile;
    	filename = 'data.txt';
    	infile = fopen(filename, "r");
    	for (i=0; i<n; i++)
    	{
    		fgets(line, 80, infile);
    		sscanf(line, "&#37;s%d", table[i].name, &table[i].age);
    		// name is a string, ie already an address!
    	}
    	fclose(infile);
    }
    void print_table(struct entry list[], int n)
    {
    	int i;
    	FILE *outfile;
    	char filename[21];
    	printf("\ntype OUTPUT FILE NAME %s", filename);
    	scanf("%s", filename);
    	outfile = fopen(filename, "w");
    	if (outfile == NULL)
    	{
    		printf("\ncannot open output file %s\n", filename);
    		exit (1);
    	}
    	for (i=0; i<n; i++)
    		fprintf(outfile, "%s\t%d\n", list[i].name, list[i].age);
    	fclose(outfile);
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #35
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    sozz i copied it out of notepad and notepad messed it up cheers for the formating does make it read better cheers for the link

  6. #36
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Here's another problem:
    Code:
    filename = 'data.txt';
    First, ' is for string literals, or in other word characters. Such as 'a', 'b', 'z', etc. Not 'abc'. That is a string and must be represented with ". So, 'a' and "abc".
    Second, you can't assign strings simply like filename = "data.txt";
    No sir. Doesn't work that way. You need to use strcpy.

    And while you read like this:
    Code:
    sscanf(line, "%s%d", table[i].name, &table[i].age);
    I doubt it's right.
    %s will continue reading until '\0' is found (or maybe '\n' too?); probably not what you want.
    You need to parse the line and copy the strings out of there using a method such as the one I demonstrated.
    Numbers can be extracted using strtol.
    Last edited by Elysia; 03-05-2008 at 07:21 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #37
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    after hours of attempts i still cant get anything out i may skip it

    this is what i was told to do

    Initialise: Reads items from data file and stores in appropriate data
    structures. 10 place names and distances between them. 10 MARKS

    my lack of knowledge is letting me down

    i dont suppose anyone else knows a betetr way to approach this becuase i am gettign no where
    Last edited by fortune2k; 03-05-2008 at 08:34 PM.

  8. #38
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Yes -- here is a better way.

    First, notice that each string and number and "-" contains no spaces. And as scanf's &#37;s stops reading when it encounters spaces, you could break up strings, numbers, and hyphens alike with %s. Then you could later try converting those strings to numbers.

    It's actually easier in this case if you use fscanf() and forgo line-by-line reading entirely. Of course, this latter method is better for error checking. I'll show you examples of both methods, but fscanf() comes first because it's easiest.

    So . . . here's your data.
    Code:
    London Bath Cardiff Carlisle Durham Exeter Leeds Norwich Truro York
    London - 23 12 89 456 123 46 732 345 123
    Bath 23 - 46 234 123 46 89 234 567 90
    Cardiff 12 46 - 767 456 46 234 123 732 35
    Carlisle 89 234 767 - 732 32 48 67 98 100
    Durham 456 123 456 732 - 234 46 89 89 732
    Exeter 123 46 46 32 234 - 123 46 123 234
    Leeds 46 89 234 48 46 123 - 46 89 19
    Norwich 732 234 123 67 89 46 46 - 123 732
    Truro 345 567 732 98 89 123 89 123 - 78
    York 123 90 35 100 732 234 19 732 78 -
    You have 10 strings, followed by 10 lines which consist of a string and 10 numbers. Reading the strings is easy:
    Code:
    char data[10][MAX_STRING_LENGTH];
    for(x = 0; x < 10; x ++) {
        fscanf(fp, "%s", data[x]);
    }
    Reading the following lines is also easy. Read one string and ten numbers, ten times, with fscanf(), of course. Problem solved. Except . . . what if you don't know how many cities there are to begin with?

    Well, in that case you can't use fscanf(), because with that function, there is no (easy) way to tell if you've read a newline or not. If you're reading it the way I've outlined, at least.

    To do this, you need to read a string, and break that up with something like sscanf(), stopping when you get to the end of the string. This is a bit involved and you need to use the %p modifier, or some annoying calculations.

    So instead of sscanf(), consider strtok(). (This is sort of what Elysia was doing.) There's a nice example of it here: http://www.cplusplus.com/reference/c...ng/strtok.html
    Code:
    /* strtok example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char str[] ="- This, a sample string.";
      char * pch;
      printf ("Splitting string \"%s\" into tokens:\n",str);
      pch = strtok (str," ,.-");
      while (pch != NULL)
      {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
      }
      return 0;
    }
    Basically, you pass it a string and the delimiters to break the string up into. (You'd probably use " ", or " \n" with fgets(), unless you remove the newline yourself.) You keep calling it, and it keeps returning substrings, until there aren't any left.

    As an example: say you call strtok("this is a test\n", " \n"). This first call will return a pointer to "this". Call it again as strtok(NULL, " \n"); you get a pointer to "is". Again: "a". Again: "test". Note that the newline is not part of this last string, because it's in the list of delimiters. And when you call it again, strtok() returns NULL.

    Basically, everything in the list of delimiters will be ignored and not included in the returned strings. And you'll get a pointer to any string that, once delimiters are removed, is longer than 0 characters. So splitting "http://www" with delimiters ":/" would give you "http" and "www".

    In short:
    Code:
    char buffer[BUFSIZ], *p;
    const char *delim = " ";
    
    if(!fgets(buffer, sizeof(buffer), fp)) {
        /* EOF or file error */
    }
    
    for(p = strtok(buffer, delim); p; p = strtok(NULL, delim)) {
        printf("Got a string: \"%s\"\n", p);
    }
    Then, having gotten these strings, you can finally use sscanf() (or strtol()) to convert them. I think sscanf() is simpler in this case.
    Code:
    if(sscanf(string, "%d", &number) != 1) {
        /* an error -- string did not contain a number */
        /* perhaps it was a string or "-" */
    }
    else {
        printf("Got a number: %d\n", number);
    }
    The *scanf() functions return the number of items successfully read. Basically, count the number of format specifiers (%d, %s, and so on) that you passed it. If the return value isn't this, something went wrong. Perhaps only some of the format specifiers could be satisfied; perhaps EOF was encountered.

    Anyway. Hopefully that will help somewhat.
    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.

  9. #39
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    right i have been trying alll night sooo i think im going to skip this part and do the rest of the program. but thank all of you for the help sooo farrr

    im going to use a String array and then come back to that part when the rest of the program is working
    right i have this String which ive taken from my java program



    Code:
       String chart1 [11][11] = // Array for the Table and Plot points
       {"London", "Bath", "Cardiff", "Carlisle", "Durham", "Exeter", "Leeds", "Norwich", "Truro", "York"},
       {"London", "-", "23", "12", "89", "456", "123", "46", "732", "345", "123"},
       {"Bath", "23", "-", "46", "234", "123", "46", "89", "234", "567", "90"},
       {"Cardiff", "12", "46", "-", "767", "456", "46", "234", "123", "732", "35"},
       {"Carlisle", "89", "234", "767", "-", "732", "32", "48", "67", "98", "100"},
       {"Durham", "456", "123", "456", "732", "-", "234", "46", "89", "89", "732"},
       {"Exeter", "123", "46", "46", "32", "234", "-", "123", "46", "123" "234"},
       {"Leeds", "46", "89", "234", "48", "46", "123", "-", "46", "89", "19"},
       {"Norwich", "732", "234", "123", "67", "89", "46", "46", "-", "123", "732"},
       {"Truro", "345", "567", "732", "98", "89", "123", "89", "123", "-", "78"},
       {"York", "123", "90", "35", "100", "732", "234", "19", "732", "78", "-"};
    and it is outputed using this
    Code:
       for(row=0; row<11;row++) // outputs the array in  2 loops 
                   {                  
    
                          for(col=0;col<11;col++)
                          {
                             printf("%6d",chart[row][col]);
                          }
                       
                     printf("\n\n");   			 
                   }
    in java that works and because i havent learnt about array strings in C yet i dont know how to copy that idea and make it work in a C program. i under stand that C uses like char[21] ect for charactersa and the last bit is \0

  10. #40
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Dude, that is way more than 11 rows. You can't specify 11 when you obviously use far more of them.
    Plus "String" is not a keyword.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #41
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    I understand that thats been copied form my java program i dont know that much bout arrays and strings whats why im asking you to find out howww to implement that as an array all it needs to do is be able to print out on the screen in a grid

  12. #42
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
       char chart1 [11][] = // Array for the Table and Plot points
       {"London", "Bath", "Cardiff", "Carlisle", "Durham", "Exeter", "Leeds", "Norwich", "Truro", "York"},
       {"London", "-", "23", "12", "89", "456", "123", "46", "732", "345", "123"},
       {"Bath", "23", "-", "46", "234", "123", "46", "89", "234", "567", "90"},
       {"Cardiff", "12", "46", "-", "767", "456", "46", "234", "123", "732", "35"},
       {"Carlisle", "89", "234", "767", "-", "732", "32", "48", "67", "98", "100"},
       {"Durham", "456", "123", "456", "732", "-", "234", "46", "89", "89", "732"},
       {"Exeter", "123", "46", "46", "32", "234", "-", "123", "46", "123" "234"},
       {"Leeds", "46", "89", "234", "48", "46", "123", "-", "46", "89", "19"},
       {"Norwich", "732", "234", "123", "67", "89", "46", "46", "-", "123", "732"},
       {"Truro", "345", "567", "732", "98", "89", "123", "89", "123", "-", "78"},
       {"York", "123", "90", "35", "100", "732", "234", "19", "732", "78", "-"};
    Code:
    for (int i = 0; i < (rows); i++)
    {
    	puts(chart1[i]);
    }
    Beware that variables must be defined at the beginning of the function in C.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #43
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    OK thankyou Elysia i shalll continue with this program

  14. #44
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    If it has not been mentioned yet, you can possibly get Visual Studio for free if you are a full time student:

    https://downloads.channel8.msdn.com/

    If you are still needing a good IDE

  15. #45
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    Quote Originally Posted by slingerland3g View Post
    If it has not been mentioned yet, you can possibly get Visual Studio for free if you are a full time student:

    https://downloads.channel8.msdn.com/

    If you are still needing a good IDE
    oooo cheers i shall check it out as i am a full time student thanks alot

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, 07: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, 03:58 PM