Suppose I have a txt file that looks like this, where there is only one space between the number and the string:
123 apple
23 pie
3456 water
How can I save apple, pie, and water to an array?
You have a many solutions for this case, i propose some solutions for reading the string from your file:
using fscanf
, see one example: ``scanf() and fscanf() in C
using fgets
to read line by line then using ssanf
to read the string from each line, see the examples: sscanf() and fgets
For storing the string in an array, you can use the 2D array or the array of char pointer:
char str_array[100][256]; // maximum 100 row and max length of each row ups to 256.
// OR
// You have to allocate for two declarations, and do not forget to free when you do not still need to use them below
char *str_array[100];
char **str_array;
For copy string to string, you should use strcpy
function. Do not use =
to assign string to string in c.
For example, i use fscanf
:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp = fopen("input.txt", "r");
if(!fp) {
return -1;
}
char line[256];
char array[100][256];
int a, i = 0;
while(fscanf(fp, "%d %255s",&a, line) == 2 && i < 100) {
strcpy(array[i], line);
i++;
}
// print the array of string
for(int j = 0; j < i; j++ ) {
printf("%s\n", array[j]);
}
fclose(fp);
return 0;
}
The input and output:
#cat input.txt
123 apple
23 pie
3456 water
./test
apple
pie
water
//This code will read all the strings in the file as described
FILE *fp = fopen("file.txt","r"); //open file for reading
int n = 3;
char *list[n]; //for saving 3 entities;
int i,a;
for(i=0;i<n;i++)
list[i] = (char *)malloc(sizeof(char)*10); //allocating memory
i = 0;
while(!feof(fp))
fscanf(fp," %d %s",&a,list[i++]);
printf("%s %s %s\n",list[0],list[1],list[2]);