![]() |
| | #1 |
| Registered User Join Date: Sep 2008
Posts: 19
| how do you input data from a file into an array? 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 1 1 ...and (column 1) index of the array, i -- an integer; (column 2) value of element iin array x, x[i] -- a double value (column 3) value of element i in array y, y[i] so i for example when i do my first loop i should get this x[1]=1 y[1]=1 and my second loop x[2]=1 y[2]=1. i know how to open file and work with loops, but i dont know how to make my first column the index of the array, and my second column the value of the element and so on. so any help would be appreciated. so it should look something like this Code: #include <stdio.h>
int main()
{
FILE *inp;
int input_status;
int n;
inp = fopen("xy.txt", "r"); //opens files
input_status = fscanf(inp, "%d", &n); //takes digits
while (input_status != EOF) //loop repeats till end of file
{
printf( "%d\n",n);// instead of this i need something that assigns it to i, and to the value of the element in array x, x[i]
input_status = fscanf(inp, "%d", &n);
}
fclose(inp);
}
Last edited by jorgejags; 11-03-2008 at 11:57 AM. |
| jorgejags is offline | |
| | #2 |
| Registered User Join Date: Oct 2008 Location: TX
Posts: 1,262
| |
| itCbitC is offline | |
| | #3 |
| Registered User Join Date: Sep 2008
Posts: 19
| yeah those are the index of the array. |
| jorgejags is offline | |
| | #4 |
| Registered User Join Date: Nov 2008 Location: Sweden
Posts: 5
| I guess you have to use the fscanf function twice. First you read the index number, then the two values. |
| Oester is offline | |
| | #5 |
| Registered User Join Date: Sep 2008
Posts: 19
| thanks. |
| jorgejags is offline | |
| | #6 |
| Registered User Join Date: Oct 2008 Location: TX
Posts: 1,262
| You can read each input line with a single fscanf() and do the assignments in the next step as in Code: #include <stdio.h>
int main(void)
{
int x[10], y[10];
FILE *inp;
int ret, l, m, n;
inp = fopen("file.txt", "r");
while ((ret = fscanf(inp, "%d%d%d", &n, &m, &l)) != EOF && ret == 3) {
x[n-1] = l;
y[n-1] = m;
printf("n = %d\nx[%d] = %d\ny[%d] = %d\n", n, n-1, m, n-1, l);
}
fclose(inp);
}
|
| itCbitC is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Data Structure Eror | prominababy | C Programming | 3 | 01-06-2009 09:35 AM |
| About aes | gumit | C Programming | 13 | 10-24-2006 03:42 PM |
| Dikumud | maxorator | C++ Programming | 1 | 10-01-2005 06:39 AM |
| Possible circular definition with singleton objects | techrolla | C++ Programming | 3 | 12-26-2004 10:46 AM |
| simulate Grep command in Unix using C | laxmi | C Programming | 6 | 05-10-2002 04:10 PM |