简体   繁体   English

如何从文本文件中获取字符串到C中的数组

[英]How to get strings from a text file to array in C

I am trying to read a list of strings from a text file and put that into an array with n words.If instead of all the lines of text I need only the first two, I would make my array of size 2 and set n = 2. However when I pass the number of words in as an argument I receive a segmentation fault, if n is not equal to the number of words in the list, and the entire list will still print.我正在尝试从文本文件中读取一个字符串列表,并将其放入一个包含 n 个单词的数组中。 2. 但是,当我将字数作为参数传入时,我收到分段错误,如果 n 不等于列表中的字数,则仍会打印整个列表。 How can I control how many words my array will hold while keeping track of my next string in the list?如何在跟踪列表中的下一个字符串的同时控制我的数组将包含多少个单词?

My text file looks like this: AH12M8 N\\n AD34FU O\\n APD83H O\\n LKFU29 N\\n我的文本文件如下所示:AH12M8 N\\n AD34FU O\\n APD83H O\\n LKFU29 N\\n

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char * argv[])
{
    FILE *myfile;
    myfile = fopen("Test.txt", "r");
    char *numWords;
    long n = strtol(argv[1], &numWords, 10);

    if(argc != 2)
   {
        printf("Too Few Arguments");
   }
   else
   {
        char arr[n][100];
        int i = 0;
        while(fgets(arr[i],sizeof(arr),myfile)!=NULL)
        {
            arr[i][strlen(arr[i])-1] = '\0';
            i++;
        }
        int total = i;
        for(i = 0; i < total; ++i)
        {
           printf("%s\n", arr[i]);
        }
        fclose(myfile);
    }
    return 0;
}
 while(fscanf(myfile,"%[^\n]%*c",arr[i])==1)    
    {
        arr[i][strlen(arr[i])-1] = '\0';
        i++;
    }

And check value of argc before using argv[1] .并在使用argv[1]之前检查argc值。

One problem is that you only allocate space for n strings, but then you read the entire file -- so if there are more than n lines, you run off the end of your array and corrupt memory and likely crash.一个问题是,您只为n字符串分配空间,然后读取整个文件——因此,如果行数超过n行,则会超出数组的末尾并损坏内存并可能崩溃。 Another problem is that you're giving fgets the length of the ENTIRE array, not the length of a single string, so if any lines are longer than 99 characters, you run off into then next line (or off the end and crash).另一个问题是你给fgets整个数组的长度,而不是单个字符串的长度,所以如果任何行超过 99 个字符,你就会跑到下一行(或结束并崩溃)。 Fixing both problems is relatively easy:解决这两个问题相对容易:

    char arr[n][100];
    int i = 0;
    while(i < n && fgets(arr[i], sizeof(arr[i]), myfile) != NULL)
    {
        if (arr[i][strlen(arr[i])-1) == '\n')
            arr[i][strlen(arr[i])-1] = '\0';
        i++;
    }

I also changed it to only drop the last character if it is a newline -- if you have any input lines longer than 99 characters, they'll be split into multiple lines.我还将它更改为仅删除最后一个字符,如果它是换行符——如果您有任何超过 99 个字符的输入行,它们将被分成多行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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