简体   繁体   English

如何将同一列中的字符串从C中的txt文件保存到数组中

[英]How to save strings in the same column to an array from a txt file in C

Suppose I have a txt file that looks like this, where there is only one space between the number and the string:假设我有一个看起来像这样的 txt 文件,其中数字和字符串之间只有一个空格:

123 apple 123 苹果

23 pie 23 馅饼

3456 water 3456水

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:对于这种情况,您有很多解决方案,我提出了一些从文件中读取字符串的解决方案:

  1. using fscanf , see one example: `` scanf() and fscanf() in C使用fscanf ,请参见一个示例: C 中的 ``scanf() 和 fscanf()

  2. using fgets to read line by line then using ssanf to read the string from each line, see the examples: sscanf() and fgets使用fgets逐行读取,然后使用ssanf从每一行读取字符串,请参见示例: sscanf()fgets

For storing the string in an array, you can use the 2D array or the array of char pointer:要将字符串存储在数组中,可以使用 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;

For copy string to string, you should use strcpy function.要将字符串复制到字符串,您应该使用strcpy function。 Do not use = to assign string to string in c.不要使用=将字符串分配给 c 中的字符串。

For example, i use fscanf :例如,我使用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:输入和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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM