trivenibomma
asked on
how to store the file data into an array in c++
i m having a file containing the numbers as 12 3 4 67 and i want to store them in an array...
Try something like this:
#include <stdio.h>
#include <string.h>
#define TABSIZE 10 /* Number of entries in array */
#define MAX_LEN 256 /* Maximum buffer size */
main() {
FILE *f; /* Input file */
int tab[TABSIZE]; /* Table for numbers */
char buffer[MAX_LEN + 1]; /* One extra byte needed for NULL */
int count; /* Number of numbers picked up from file */
f = fopen("xx.txt", "r"); /* Open the file */
while (fgets(buffer, MAX_LEN, f)) { /* Read a line */
int iX = 0;
char *pStr = strtok(buffer, " ");
while (pStr && iX<TABSIZE) {
tab[iX++] = strtol(pStr, NULL, 10);
pStr = strtok(NULL, " ");
}
if (pStr) { /* Is the table full? */
fprintf(stderr, "The table size of %d is too small\n", TABSIZE);
}
count = iX;
}
/* Now we have "count" entries in "tab" */
printf("Found %d numbers\n", count);
fclose(f); /* Tidy up - close the file */
}
#include <stdio.h>
#include <string.h>
#define TABSIZE 10 /* Number of entries in array */
#define MAX_LEN 256 /* Maximum buffer size */
main() {
FILE *f; /* Input file */
int tab[TABSIZE]; /* Table for numbers */
char buffer[MAX_LEN + 1]; /* One extra byte needed for NULL */
int count; /* Number of numbers picked up from file */
f = fopen("xx.txt", "r"); /* Open the file */
while (fgets(buffer, MAX_LEN, f)) { /* Read a line */
int iX = 0;
char *pStr = strtok(buffer, " ");
while (pStr && iX<TABSIZE) {
tab[iX++] = strtol(pStr, NULL, 10);
pStr = strtok(NULL, " ");
}
if (pStr) { /* Is the table full? */
fprintf(stderr, "The table size of %d is too small\n", TABSIZE);
}
count = iX;
}
/* Now we have "count" entries in "tab" */
printf("Found %d numbers\n", count);
fclose(f); /* Tidy up - close the file */
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok i got it....
Does it work ? If you show your code, we can have a look at it to see if it's ok.
You'll have to read them from the file and store them. C++ has quite a few ways to do this.
Good Luck,
Kent