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; Hi, I have been set an assignment where i have to work out mileage price ect from the following chart ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    147

    Reading in data from Text file

    Hi, I have been set an assignment where i have to work out mileage price ect from the following chart which is stored as a text file ( data.txt )

    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 -

    The problem which im trying to over come is that i need to read in all the data into an array and be able to output it on screen fortmated and i need to be able to use it to work out distances ect i have been up trying for hours and hours just tring to get the program to read in from the text file and output it on screen in the grid

    i think i need like some sort of 2d string array which can read in and store the data
    can anyone help me ?


    thankoyu

  2. #2
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,823
    This calls for the read and parse method.
    Read string, preferably using fgets.
    Then keep reading (or you can search using various search functions) until you find a space to extract a string from it.
    To get a number, all you need to do is use an appropriate string to number method, such as strtol.
    And as for how to do this... it can be done via pointers and, of course, or just indexes.

    So you can reading data into a 2D array and then parse it.
    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. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    You have a few things you're trying to do. Firstly, you're trying to read strings from a file. You're also going to need to parse those strings into components, so that you can format the output and do calculations on the values. (To do the latter, you'll also have to convert strings to numbers.)

    So, yes, a 2D array of strings would probably work. Note that this is actually three dimensions, because strings themselves are arrays. Basically, you'd use something like this:
    Code:
    char data[LINES_IN_FILE][WORD_IN_LINE][CHARACTERS_IN_WORD];
    Use fgets() or something to read lines from the file, and then strtok() or even easier sscanf() or something to separate out words in the line. (Or use fscanf() and do both things at once.)

    To convert strings to numbers, you can use strtol() from <stdlib.h>, or maybe sscanf() again. See the FAQ.

    Have you started, tried, written any code?
    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. #4
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    well there its and 11 by and 11 gird i was thinking of trying to have a thing where it would read in all the data from 1 row and loop 11 times for 11 rows soo then i would gather all the data and then store it

    also i am not the best at C this is my 6th week of learning it and this week im doin learning bout getting data from text files ....its rather hard im using pelles C to write and run it is this a good IDE to use?


    i shall have a mess around with it and see what i can do

    Have you started, tried, written any code?
    im still thinking the best way to start it as im still trying to learn this stuff whilst i do it ill probs start this bit soon


    thankyou
    Last edited by fortune2k; 03-05-2008 at 01:00 PM.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Quote Originally Posted by fortune2k View Post
    ....its rather hard im using pelles C to write and run it is this a good IDE to use?
    I've never used it -- I prefer Dev-C++ or Code::Blocks -- but I've heard good things about it.

    You could have a look at some tutorials. http://www.cprogramming.com/tutorial/c/lesson10.html

    And here's a simple program that might demonstrate what we're talking about . . .
    Code:
    $ ./fortune2k 
    Enter some numbers: 2 3 4 k 5
    2
    3
    4
    Error parsing number at " k 5"
    $ cat ./fortune2k.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
        char buffer[BUFSIZ], *start, *end, *p;
        long n;
    
        printf("Enter some numbers: ");
        if(!fgets(buffer, sizeof(buffer), stdin)) {
            /* EOF or another error was encountered */
    	perror("stdin");
    	return 1;
        }
    
        /* remove the (possible) newline from buffer */
        if((p = strchr(buffer, '\n'))) *p = 0;
    
        start = buffer;
        do {
            n = strtol(start, &end, 0);
    	if(start == end || !end) {
                printf("Error parsing number at \"%s\"\n", start);
                break;
            }
    
            printf("%ld\n", n);
    	start = end;
        } while(*end);
    
        return 0;
    }
    
    $
    Okay, so that was somewhat longer than it needed to be. Look into fscanf(). It should be good enough for your purposes.
    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.

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,823
    Visual Studio is a killer IDE and is better at barfing on things that GCC. More recommended for newbies. No command lines for the compiler/linker either. It's all automatic.
    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. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Quote Originally Posted by Elysia View Post
    Visual Studio is a killer IDE
    Yeah, it kills things like standards compliance in their tracks. (Actually, that wasn't fair; MSVC 6 does, and that's the only version I really used. I hear later versions are better.)

    and is better at barfing on things that GCC. More recommended for newbies. No command lines for the compiler/linker either. It's all automatic.
    You mean you recommend it for newbies, not everyone. Besides, you don't have to use the command line unless you want to -- the IDEs I mentioned can do it for you. I just like the command line.

    Have you ever used GCC? We keep arguing about this, and it would be funny if I never really used MSVC and you never really used GCC . . . .
    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.

  8. #8
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    right im start off small trying to get the first line to print out on screen and store in a String array this is what ive gotten soo far

    Code:
    #include<stdio.h>
     
    int main()
    {  
        int i=1;
       FILE *f;
       char buf[10000];
       f = fopen("data.txt","r");   
    				fgets(buf,sizeof(buf),f);
    		             printf("%s\n",buf);
    		fclose(f);
    		
       return 0;
    }
    i get the output of the first line which is
    London Bath Cardiff Carlisle Durham Exeter Leeds Norwich Truro York

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,823
    Quote Originally Posted by dwks View Post
    Yeah, it kills things like standards compliance in their tracks. (Actually, that wasn't fair; MSVC 6 does, and that's the only version I really used. I hear later versions are better.)
    You just ate your own words there.
    Indeed, 2005 & 2008 are actually very standards compliant. Bjorne himself actually mentioned that there's nothing bad with Microsoft's compilers (except for the vendor lock-in stuff of .NET).

    You mean you recommend it for newbies, not everyone. Besides, you don't have to use the command line unless you want to -- the IDEs I mentioned can do it for you. I just like the command line.
    No, for everyone. But especially for newbies.

    Have you ever used GCC? We keep arguing about this, and it would be funny if I never really used MSVC and you never really used GCC . . . .
    Yes, twice. Once a long time ago, that I really can't remember and once on a place where I had no access to Visual Studio but had to do something.
    And the IDE disgusts me. Ugly as crap. And yada, yada. But I keep my opinions to myself, as others obviously find it a good IDE.
    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.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Quote Originally Posted by Elysia View Post
    You just ate your own words there.
    How observant of you.
    Indeed, 2005 & 2008 are actually very standards compliant. Bjorne himself actually mentioned that there's nothing bad with Microsoft's compilers (except for the vendor lock-in stuff of .NET).
    Well, what about portability? I can't run it under my Linux system, besides (possibly) under Wine, which is beside the point.

    No, for everyone. But especially for newbies.
    I think Dev-C++ is much easier to use for newbies. You don't need to use projects, you can just compile a single source file. You just have a .c and a .exe if you do, none of those other mysterious files . . . .

    Yes, twice. Once a long time ago, that I really can't remember and once on a place where I had no access to Visual Studio but had to do something.
    And the IDE disgusts me. Ugly as crap. And yada, yada. But I keep my opinions to myself, as others obviously find it a good IDE.
    Umm . . . what? GCC isn't an IDE. You've obviously used Dev-C++ or something. (BTW, you can change how Dev-C++ looks . . . I don't really like the default theme, either. Too blue.)

    [edit] fortune2k, looks good -- remember, however, that fgets() keeps the newline it read from the file, if any. You'll probably want to strip that. See my example.

    Now try reading all the lines in the file -- something like this:
    Code:
    while(fgets(buffer, sizeof(buffer), fp)) {
        /* ... */
    }
    [/edit]
    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.

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,823
    Quote Originally Posted by dwks View Post
    Well, what about portability? I can't run it under my Linux system, besides (possibly) under Wine, which is beside the point.
    Obviously not, but so what? What is important is that it can create portable code.
    It may be a shame, but it's not a (very) bad thing.

    I think Dev-C++ is much easier to use for newbies. You don't need to use projects, you can just compile a single source file. You just have a .c and a .exe if you do, none of those other mysterious files . . . .
    Nonsense, I say. There's no harm in projects. It's not difficult anyway.
    I don't see the harm in projects, or the complexity.

    Umm . . . what? GCC isn't an IDE. You've obviously used Dev-C++ or something. (BTW, you can change how Dev-C++ looks . . . I don't really like the default theme, either. Too blue.)
    OF course, I mean a Windows distribution such as mingw or whatever it's called. It comes with the GCC compiler. The GUI is awful, and the compiler lacks narrowing conversion warnings.
    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.

  12. #12
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    right how do i make my program look for certain things like my first line in data.txt is

    London Bath Cardiff Carlisle Durham Exeter Leeds Norwich Truro York

    how can i use fget to pick up each name and store them into a string. Im finding it hard to get my head round this fget stuff and char [] ect

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,823
    First, we need to find a space that tells us it's the end of the word. We can use strtok for that.
    Then we can truncate the string by setting the space to '\0', thus setting a premature end on the string. Then you can copy the part you want using strcpy into a new buffer.
    Rinse, repeat.
    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.

  14. #14
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Obviously not, but so what? What is important is that it can create portable code.
    Umm . . . what? MSVC can't create code that is very portable. Executables are by their very nature not very portable. But at least GCC can compile the same code under Windows and Linux.

    It may be a shame, but it's not a (very) bad thing.
    Sure, it's not a bad thing . . . unless you're not using Windows. Then you can't take advantage of MSVC's "superior" warnings.

    Nonsense, I say. There's no harm in projects. It's not difficult anyway.
    I don't see the harm in projects, or the complexity.
    It's quite a bit more complicated. There are extra clicks involved and extra files.

    OF course, I mean a Windows distribution such as mingw or whatever it's called. It comes with the GCC compiler. The GUI is awful,
    Dev-C++. mingw is a Windows port of GCC. Dev-C++ is a GUI (written in Delphi ) that can run GCC, the mingw or the cygwin ports.

    and the compiler lacks narrowing conversion warnings.
    Food for thought -- GCC might not support narrowing warnings, but MSVC doesn't support long doubles, AFAIK. http://www.thescripts.com/forum/thread61148.html
    That's more important, I think; the warning isn't strictly required, but long doubles are for C99.

    [edit]
    First, we need to find a space that tells us it's the end of the word. We can use strtok for that.
    Then we can truncate the string by setting the space to '\0', thus setting a premature end on the string. Then you can copy the part you want using strcpy into a new buffer.
    Rinse, repeat.
    I thought of that too . . . but sscanf() would be simpler, especially since most of the data is numbers, anyway.

    For example:
    Code:
    char str[] = "name 12 56";
    char name[10];
    int one, two;
    sscanf(str, "&#37;s%d%d", name, &one, &two);
    printf("name: \"%s\"    one: %d    two: %d\n", name, one, two);
    I know it's scanf("%s"), but still . . . . [/edit]
    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.

  15. #15
    Registered User
    Join Date
    Mar 2008
    Posts
    147
    Quote Originally Posted by dwks View Post
    [CODE]
    Now try reading all the lines in the file -- something like this:
    Code:
    while(fgets(buffer, sizeof(buffer), fp)) {
        /* ... */
    }

    ok sooo what does the " buffer, sizeof(buffer" do



    lol thisss iss rather hardd

Page 1 of 15 1234567891011 ... LastLast
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