Thread: splitting a .txt into 2 diff arrays

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    4

    splitting a .txt into 2 diff arrays

    Hi all,

    im new to programming and new to C, just started with arrays and im somewhat stucked, where i have a .txt file which contains items and prices. I want the items and the prices split into 2 different arrays

    The .txt looks like that:

    orange 0.89
    banana 0.79
    apple 0.59

    I now want to split the items in a char items[100][100] and float prices[100]. Can somebody show me how to split this, preferably with fscanf ?

  2. #2
    Registered User
    Join Date
    May 2013
    Posts
    228
    Hi Zator.
    What have you tried so far?

  3. #3
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    We are here to help but there are tons of solutions in these forums. I quick search for me for what you may be after was found here: CString split function ?

  4. #4
    Registered User
    Join Date
    Oct 2014
    Posts
    4
    so i have

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h> 
    #include <string.h> 
    
    
    int main() {
    
    char filename[] = "test.txt";
        FILE * file;
        char items[100]; // [100][100];
        // float prices[100]
    
        file = fopen(filename,"r");
        if (file == NULL){
            perror(filename);
            return 1;
            }
        while (fscanf(file,"%s", items) == 1){
            printf("%s\n", items);
            }
            fclose(file);
    }
    Thats where im currently stucked. As you can see i am only using 1 array which presents the line. I have problems putting char[100][100] in, cause i dont know the notations for the while part then (gettin lots of errors etc.). Right now hes printing the completely .txt file like

    orange
    0.89
    banana
    0.79
    apple
    0.59

    but i want it like this.
    Dont want to print it tho (just looking if its okay).
    He should give back the number of lines(=elements).

    item array

    orange
    banana
    apple

    price array

    0.89
    0.79
    0.59

  5. #5
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by Zator View Post
    so i have

    Code:
         while (fscanf(file,"%s", items) == 1){
            printf("%s\n", items);
            }

    This will only read individual items. You probably want to read pairs. For example your data file has this line:

    orange 0.89

    Then you want to read this into an item, price pair. I think the best way is to read individual lines and then process them with sscanf. For example, suppose you read in a line by using fgets into buf, then you could do the following:

    Code:
    char item[100];
    float price;
    char c;
    
    if (sscanf(buf, "%99s %f %c", item, &price, &c) != 2) {
        printf("Line is not in correct format: expected item price\n");
        exit(1);
    }
    This makes sure each line has the two tokens you need (item, price) and nothing else. The %99s ensures that item fits into a 100 byte buffer. If you declare your array as you said initially with char items[100][100] then you can simply copy them into your array at this point.

    Code:
    strcpy(items[nitems++], item);
    prices[nprices++] = price;
    Repeat this for all remaining lines. You should also add a check to stop reading lines as soon as nitems or nprices reaches 100.
    Last edited by c99tutorial; 10-21-2014 at 10:29 AM.

  6. #6
    Registered User
    Join Date
    Oct 2014
    Posts
    4
    Well i want to do it with fscanf. Can you help me whats wrong here?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h> 
    #include <string.h> 
    
    #define MAX_LINES 100
    #define MAX_LENGTH 100
    
    int read_pricelist(const char* filename, char items[MAX_LINES][MAX_LENGTH], float prices[MAX_LINES]) {
    
    
      FILE *file;
      file = fopen("./prices.txt","r");
      if (file == NULL){
        perror("-1");
        exit(1);
      }
    
      while(!feof(file)) {
        fscanf(file, "%s %f", &items, &prices);
        printf("read %s %f\n", items, prices);
    
      }
      fclose(file);
    }
    
    int main() {
    
    }

    i basically get this error for every: %s’ expects argument of type ‘char *’, but argument 3 has type ‘char (**)[100]’ and
    ‘%f’ expects argument of type ‘float *’, but argument 4 has type ‘float **’

  7. #7
    Registered User
    Join Date
    Oct 2014
    Posts
    4
    It is error free now, but somehow its not printing anything.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h> 
    #include <string.h> 
    
    #define MAX_LINES 100
    #define MAX_LENGTH 100
    
    void read_pricelist(const char* filename, char items[MAX_LINES][MAX_LENGTH], float prices[MAX_LINES]) {
    
    int i;
    
    
      FILE *file;
      file = fopen("./prices.txt","r");
      if (file == NULL){
        perror("Reading from file prices.txt");
        exit(1);
      }
      i = 0;
      while(!feof(file)) {
        fscanf(file, "%s %f", items[i], &prices[i]);
        printf("%s %f\n", items[i], prices[i]);
        i++;
      }
      fclose(file);
    }
    Any help here?

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Perhaps you forgot to call the read_pricelist function?

    Also, you should not use feof to control the loop in that way. Rather, use the return value of fscanf:
    Code:
    i = 0;
    while (fscanf(file, "%s %f", items[i], &prices[i]) == 2) {
        printf("%s %f\n", items[i], prices[i]);
        i++;
    }
    However, this is still problematic in that items[i] presumably can store a string at most MAX_LENGTH - 1 in length. You need to account for this when reading to avoid buffer overflow, e.g.,
    Code:
    char scan_format[16];
    sprintf(scan_format, "%%%ds %%f", MAX_LENGTH - 1);
    i = 0;
    while (fscanf(file, scan_format, items[i], &prices[i]) == 2) {
        printf("%s %f\n", items[i], prices[i]);
        i++;
    }
    Also, it would probably be better to return an error code instead of exiting immediately if the file cannot be opened. Perhaps at some later point you might want to allow the user to try again with a different file name.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Splitting dynamically allocated 2D arrays
    By CodeNovice in forum C Programming
    Replies: 1
    Last Post: 06-25-2014, 11:46 AM
  2. Splitting an int array into four arrays
    By zak9000 in forum C Programming
    Replies: 2
    Last Post: 01-02-2012, 06:08 PM
  3. why does this code do something diff on 2 diff boxes?
    By crypto_quixote in forum C Programming
    Replies: 3
    Last Post: 03-08-2005, 12:11 PM
  4. structures and arrays. Whats the diff?
    By correlcj in forum C Programming
    Replies: 9
    Last Post: 08-05-2002, 04:01 PM
  5. Diff compiler == diff program????
    By Imperito in forum C++ Programming
    Replies: 21
    Last Post: 04-25-2002, 12:50 PM