In: Computer Science
Using c programming language
How do you put data from a text file into a 2d array
For example a text file with names and age:
john 65
sam 34
joe 35
sarah 19
jason 18
max 14
kevin 50
pam 17
bailey 38
one 2d array should have all the names from the file and one 2d array should have all the ages and both arrays should be printed out separately and be 3x3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp;
int r;
//open the input file
fp = fopen("input.txt", "r");
char name[100];
int age;
//create the arrays
char names[9][100];
int ages[9];
int i = 0;
//read the file line by line
while((r = fscanf(fp, "%s %d", name, &age) !=
EOF))
{
//store the name into the
array
strcpy(names[i], name);
//sotre the age into the
array
ages[i] = age;
i++;
}
//printing all the names in the array
printf("Names:\n");
//iterate over the array
for(int i = 0;i < 9;i++)
{
//print the names
printf("%s\n", names[i]);
}
//printing all the names in the array
printf("Ages:\n");
//iterate over the array
for(int i = 0;i < 9;i++)
{
//print the ages
printf("%d\n", ages[i]);
}
}