首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C中读取文件并存储为int

在C中读取文件并存储为int
EN

Stack Overflow用户
提问于 2014-10-25 08:49:29
回答 2查看 94关注 0票数 0

这是一个场景。我在一个文件中有一个矩阵,其中包含数字和字母x。x表示没有出现路径。我正在尝试读取一个文件并将其存储在一个int数组中。但它并不能很好地工作。X的值不会更改为99999。

代码语言:javascript
运行
复制
graph.txt
0 x x x x x
x 0 x x x x
x x 0 x x x
x x x 0 x x
x x x x 0 x
x x x x x 0

this is the result. 

 0    2291852    1988293161    5507688    2291916    1988315945
 3    1988315897    1238539516    3    1988897120    0
 3    0    1988897120    2291908    1988273218    5508800
 2291920    1988293445    19    2291976    1988390633    1988897120
 1988390584    1238539576    2293452    0    2293256    2291936
 1988339419    2293700    1988398293    1064569584    160    0

以下是代码

代码语言:javascript
运行
复制
 # define x 99999
 int main(){

char filename[200]="";

char buffer[200];

int ch;

FILE * fileIn;

FILE * fileInn;

    printf("\tEnter Filename> ");

    scanf("%s", &filename); //Enter filename


        if((fileIn = fopen(filename, "r")) == NULL) { //error filename

            printf("File could not be opened. \n");}

        else {


            while(!feof(fileIn)){ //counts number of rows 

                    ch = fgetc(fileIn);

                    if(ch == '\n') size+=1;

            }



            rewind(fileIn);



            if(!(feof(fileIn))){ //puts the matrix in an array

                int input[size][size];

                for(a = 0; a<size; a++) {

                    for(b=0; b<size; b++) {

                        fscanf(fileIn, "%d", &input[a][b]);     

                    }

                }

                printMatrix(input);



            }else printf("EOF");
    }

}

我想要发生的是,当矩阵元素是x时,x将被读取为99999,并将其存储在输入数组中。如果它是一个整数,它将直接存储在输入数组中。

EN

回答 2

Stack Overflow用户

发布于 2014-10-25 10:44:41

有许多方法可以从文件中读取数组。您的挑战增加了一个简单的复杂性,即您必须从文件中读取字符和整数,然后根据字符表示数字还是单个字符'x‘将元素添加到数组中,然后将值替换为'99999’。

要做到这一点,最简单的方法是使用面向行的输入从数据文件中读取一行,然后根据需要解析每行。我建议您在满足所有行输入需求时与getline交朋友。与fgetsscanf相比,它提供了许多好处,并且不需要比其他任何一个更多的工作。

一旦从输入中读取了数据行,就需要将该行拆分成单词。strtok是首选工具,否则您可以编写自定义解析器(取决于您的需求)。strtok在这里运行得很好。将行拆分为单词时,可以对每个单词进行测试,以确定它们代表的是数字还是字符。有很多方法可以做到这一点。在您的例子中,一种简单有效的方法是测试第一个字符是否为'x'。如果是,用99999代替数组值,如果不是,只需使用atoi (word)将单词转换为整数。

以下是完成上述所有操作的一个技巧。通读一遍,如果你有任何问题,请告诉我。

oops最初有'9999‘而不是'99999’--修复了

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 1024

int main (int argc, char **argv) {

    if (argc < 2) {
        fprintf (stderr, "Error: insufficient input. Usage: %s input_file\n", argv[0]);
        return 1;
    }

    char *line = NULL;      /* forces getline to allocate space for buf */
    ssize_t read = 0;       /* number of characters read by getline     */
    size_t n = 0;           /* limit number of chars to 'n', 0 no limit */
    int idx = 0;            /* simple index counter for array           */
    int row = 0;            /* simple row counter index for array       */
    int *col = NULL;        /* simple column counter for array          */
    int *array = NULL;      /* array to hold integers read from file    */
    char *delim = " \n";    /* delimeter for strtok to parse line       */

    FILE *ifp = fopen(argv[1],"r");
    if (!ifp)
    {
        fprintf(stderr, "\nerror: failed to open file: '%s'\n\n", argv[1]);
        return 1;
    }

    array = calloc (MAX_SIZE, sizeof (array));      /* allocate MAX_SIZE elements           */
    col   = calloc (MAX_SIZE, sizeof (col));        /* allocate MAX_SIZE elements           */

    while ((read = getline (&line, &n, ifp)) != -1) /* read each line in file with getline  */
    {
        char *tmp = NULL;                           /* pointer to hold strtok results       */

        tmp = strtok (line, delim);                 /* first call to strtok using 'line'    */

        if (*tmp == 'x')                            /* test if tmp[0] = 'x'                 */
            array [idx++] = 99999;                  /* if so, assign value of '99999'       */
        else
            array [idx++] = atoi (tmp);             /* if not, assign result of atoi (tmp)  */

        col[row]++;                                 /* increase column count                */

        while ((tmp = strtok (NULL, delim)) != NULL) /* all remaining strtok calls use NULL */
        {
            if (*tmp == 'x')                        /* same tests as above                  */
                array [idx++] = 99999;
            else
                array [idx++] = atoi (tmp);

            col[row]++;                             /* increase column count                */

        }
        row++;                                      /* increase row count                   */
    }

    if (line) free (line);                          /* free memory allocated by getline     */

    int it = 0;                                     /* simple index iterator                */

    while (col[it])                                 /* simple loop to validate columns      */
    {
        if (it > 0)
            if (col[it-1] != col[it])
            {
                fprintf (stderr, "Error: inconsistent colums of data read\n");
                return 0;
            }
        it++;
    }

    printf ("\nProperties of array read from file '%s':\n\n", argv[1]);
    printf ("  elements: %d\n  rows    : %d\n  cols    : %d\n", idx, row, col[0]);

    printf ("\nArray elements:\n\n");

    for (it = 0; it < idx; it++)                    /* output information stored in array   */
    {
        if ((it+1) % col[0] == 0 && it > 0)
            printf (" %5d\n", array[it]);
        else
            printf (" %5d", array[it]);
    }
    printf ("\n");

    if (array) free (array);                        /* free memory allocated to arrays      */
    if (col)   free (col);

    return 0;
}

输入文件:

代码语言:javascript
运行
复制
$ cat dat/graph.txt
0 x x x x x
x 0 x x x x
x x 0 x x x
x x x 0 x x
x x x x 0 x
x x x x x 0

输出:

代码语言:javascript
运行
复制
$ /bin/rgraph dat/graph.txt

Properties of array read from file 'dat/graph.txt':

  elements: 36
  rows    : 6
  cols    : 6

Array elements:

     0 99999 99999 99999 99999 99999
 99999     0 99999 99999 99999 99999
 99999 99999     0 99999 99999 99999
 99999 99999 99999     0 99999 99999
 99999 99999 99999 99999     0 99999
 99999 99999 99999 99999 99999     0
票数 3
EN

Stack Overflow用户

发布于 2014-10-25 08:58:41

#define x 99999告诉编译器将符号x视为程序中的值99999;它对如何处理从文件中读取的字符没有任何影响。

既然您显式地告诉fscanf您希望读取一个整数,那么就没有理由期望它是合理的(因为您刚才对它撒了谎话)。

您可以做的是以字符串的形式读取每个符号,如果它是一个x,则执行适合您的程序的任何操作;您可以使用像sscanfatoi这样的实用工具来处理那些实际上是整数的符号。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26558251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档