Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
C Programming: How to store info from text file into array?
I have a text file of following format that I need to store in array.
StudentID FirstName
1031 Kelly
1052 Ryan
2012 Taylor
1821 Katharine
1963 Michael
Preferably, I want to store into a 2-D array, but one dimensional may be fine.
I have asked this question before but haven't got any helpful answers. Please help.
3 Answers
- 1 decade agoFavorite Answer
Hello,
Your text file is an unstructured one.
Still you should store the numbers as the string if you want to store both columns in one array. But I suggest that you use two 1-D arrays: one integer array for the numbers and a string array for the names.
You can read the data in file using the following code:
Two 1-D arrays:
////////////////////////////
FILE *fp;
char *StrArr[5];
int NumArr[5];
fp = fopen("filename.txt", "r");
for(int i=0; i<6; i++)
fscanf(fp, "%d %s\n", &NumArr[i], &StrArr[i]);
///////////////////////////
- ?Lv 45 years ago
you at the instant are not analyzing categories of archives, yet purely text fabric chars it may look. the only trouble is which you're able to be able to desire to have the potential to forget approximately areas, commas, carriage returns, and parenthesis as white area separators, jointly as recognizing multi char strings while there is not any white area or separators. So often you have 2 nested jointly as loops. the 1st is going till eof, to technique each and every of the techniques, each and every chew going right into a diverse string of the string array. the 2d is the single that gets each and every of the char in one string. it may first pass over any white area or separator, till it gets a stable commencing char. Then it keeps accumulating till it hits a white area or separator, which terminates the string and ends the internal loop. undergo in recommendations that strings are basically an array of chars, so as subsequently that's a 2 dimensional array of chars you're filling.
- samiLv 51 decade ago
i dont think you can fit different data types into one single array.
you have both a string and an int.
you should declare a data structure like this:
typedef struct student_type
{
char name[20];
int ID;
} student_type;
which you can instantiate like :
student_type Fred, Bill;
and add values to them like :
Fred.ID= 123;
Fred.name= "Greenberg";
...
and finally you can either have an array of student_type if you know in advance how many entries are in the file, or in case you don't know how many entries are exactly in the file, a linked list of type student_type.