top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Splitting text into two different arrays?

+4 votes
54 views

New to programming and C, I have a .txt file which contains items and prices. I want the items and the prices split into 2 different arrays

My text file looks like:

orange 1.23
banana 1.56
apple 1.89

I now want to split the items in a char items[100][100] and float prices[100]. Please help.

posted Oct 24, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Here is my code (Tested).
One catch here before storing the float value you have to converter string which has value float using the function <atof() //for more info see the man page >.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE *fp = NULL;
    char item[10][100], temp[200];
    char *t, *delm = " \n";
    int i = 0, j = 0, k = 0;
    float price[10];

    fp = fopen("f.txt", "r+");
    if (fp == NULL)
        return -1;

    while(fgets(temp, 200, fp) != NULL) {

        t = strtok(temp, delm);
        while (t) {

            if (i++ % 2)
                price[j++] = atof(t);
            else
                strcpy(item[k++], t);

            t = strtok(NULL, delm);

        }
    }

    for (k = 0; k < j; k++)
        printf("item : %s ---> price : %.2f\n", item[k], price[k]);


    fclose(fp);

    return 0;
 }
answer Oct 26, 2014 by Arshad Khan
Similar Questions
+3 votes

Input:
[1 7 15 29 11 9]

Output:
[9 15] [1 7 11 29]

Average of first part: (15+9)/2 = 12,
Average of second part: (1 + 7 + 11 + 29) / 4 = 12

+1 vote

What is the overhead in splitting a for-loop like this,

int i;
for (i = 0; i < exchanges; i++)
{
    // some code
    // some more code
    // even more code
}

into multiple for-loops like this?

int i;
for (i = 0; i < exchanges; i++)
{
    // some code
}
for (i = 0; i < exchanges; i++)
{
    // some more code
}
for (i = 0; i < exchanges; i++)
{
    // even more code
}

The code is performance-sensitive, but doing the latter would improve readability significantly. (In case it matters, there are no other loops, variable declarations, or function calls, save for a few accessors, within each loop.)

I'm not exactly a low-level programming guru, so it'd be even better if someone could measure up the performance hit in comparison to basic operations, e.g. "Each additional for-loop would cost the equivalent of two int allocations." But, I understand (and wouldn't be surprised) if it's not that simple.

+2 votes
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...