Thread: Reading a file to variables

  1. #1

    Question Reading a file to variables

    I want to make a program that can read a normal txt file and set certain lines to certain variables...

    heres an example, say i have,
    int a, b, c, d;
    and then the file looks like this...

    this is my file
    b: 2
    and other stuff in between the values i want.
    d: 8
    and so on
    a: 1
    so i have a pretty much jumbled file
    c: 9

    and then i want my code to go through the file and set variables according to the file, i.e b=2 etc... i was thinking of using strcmp to search the file a: b: etc..., but then how could i put the value thats directly after the target into the variable

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    use seekp (or seekg, i forget which one) if you're using an fstream. use google for documentation on those.

  3. #3
    Registered User Dual-Catfish's Avatar
    Join Date
    Sep 2001
    char numeric[] =  "1234567890";
    int a, b, c, d;
    char buf[20];
    ifstream fin("filename.txt");
    while (!ifstream.eof())
          ifstream.getline(buf, 19, '\n');
          char *found = strpbrk(buf, numeric);
          int extractedDigit = atoi(found);
                case 'a': a = extractedDigit;
                // ...
    You could use something like that. (Hell, I hope that works) Although, with a little added complexity, i'm pretty sure you could trash the switch statement for a token pasting macro.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM