[英]C language help:How to store strings from a .txt file into a character array? This .txt file is read from a command line argument btw.
[英]How to save strings in the same column to an array from a txt file in C
假设我有一个看起来像这样的 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
function。 不要使用=
将字符串分配给 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;
}
输入和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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.