假设我有一个类似于这样的txt文件,数字和字符串之间只有一个空格。
123苹果
23个馅饼
3456水
如何将苹果、派、水保存到一个数组中?
对于这种情况,你有很多解决方案,我提出一些从你的文件中读取字符串的解决方案。
使用 fscanf
见一个例子:``C中的scanf()和fscanf()。
如果要将字符串存储在一个数组中,可以使用2D数组或char指针数组。
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;
如果要把字符串复制到字符串中,应该使用 strcpy
功能。不要使用 =
将字符串赋值给c中的字符串。
例如,我用 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;
}
输入和输出。
#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]);