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

文件读取并在C中存储为int,c,C,下面是一个场景。我有一个包含数字和字母x的文件中的矩阵。x表示没有路径出现。我试图读取一个文件并将其存储在int数组中。但效果不好。x的值不会更改为99999 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

下面是一个场景。我有一个包含数字和字母x的文件中的矩阵。x表示没有路径出现。我试图读取一个文件并将其存储在int数组中。但效果不好。x的值不会更改为99999

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
这是密码

 # 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 99999
int main(){
字符文件名[200]=“”;
字符缓冲区[200];
int-ch;
文件*fileIn;
文件*fileInn;
printf(“\tEnter Filename>”);
scanf(“%s”,&filename);//输入文件名
如果((fileIn=fopen(filename,“r”))==NULL){//错误文件名
printf(“无法打开文件。\n”);}
否则{
而(!feof(fileIn)){//统计行数
ch=fgetc(文件输入);
如果(ch=='\n')大小+=1;
}
倒带(文件输入);
如果(!(feof(fileIn)){//将矩阵放入数组中
int输入[size][size];
for(a=0;a
#define x 9999
告诉编译器将符号
x
视为程序中的值99999;它对如何处理从文件读取的字符没有影响

由于您明确地告诉fscanf
您希望读取一个整数,因此没有理由期望它具有任何合理的含义(因为您只是对它撒谎)

您可以将每个符号作为字符串读取,如果它是
x
,则执行适合您的程序执行的任何操作;您可以使用
sscanf
atoi
之类的实用程序来处理那些实际上是整数的符号。

定义x 99999
告诉编译器将符号
x
视为value 99999;它对如何处理从文件读取的字符没有影响

由于您明确地告诉fscanf您希望读取一个整数,因此没有理由期望它具有任何合理的含义(因为您只是对它撒谎)

您可以将每个符号作为字符串读取,如果它是
x
,则执行适合您的程序执行的任何操作;您可以使用
sscanf
atoi
之类的实用程序来处理那些实际上是整数的符号。

定义x 99999
告诉编译器将符号
x
视为value 99999;它对如何处理从文件读取的字符没有影响

由于您明确地告诉fscanf您希望读取一个整数,因此没有理由期望它具有任何合理的含义(因为您只是对它撒谎)

您可以将每个符号作为字符串读取,如果它是
x
,则执行适合您的程序执行的任何操作;您可以使用
sscanf
atoi
之类的实用程序来处理那些实际上是整数的符号。

定义x 99999
告诉编译器将符号
x
视为value 99999;它对如何处理从文件读取的字符没有影响

由于您明确地告诉fscanf您希望读取一个整数,因此没有理由期望它具有任何合理的含义(因为您只是对它撒谎)


您可以将每个符号作为字符串读取,如果它是
x
,则执行适合您的程序执行的任何操作;您可以使用
sscanf
atoi
等实用程序来处理实际为整数的符号。

从文件读取数组的方法有很多。您的挑战增加了一个简单的复杂性声明必须从文件中读取字符和整数,然后根据字符是否表示数字或是否是单个字符“x”将元素添加到数组中,然后替换为值“99999”

最简单的方法是使用面向行的输入从数据文件中一行一行地读取数据,然后根据需要解析每一行。我建议您与
getline
交朋友,以满足所有行输入需求。与
fgets
scanf
相比,它提供了许多好处,并且不需要更多的努力韩不是其他人

从输入中读取数据行后,需要将该行拆分为单词。
strtok
是首选工具,否则可以编写自定义解析器(取决于您的需要).
strtok
在这里可以很好地工作。当您将行拆分为单词时,您可以测试每个单词,以确定它们是否表示数字或字符。有很多方法可以做到这一点。在您的情况下,一种简单有效的方法就是测试第一个字符是否为
'x'
。如果是,请用
99999
替换数组value,如果不是,只需使用
atoi(word)
将单词转换为整数即可

下面是一个黑客在做所有上述。通读它,让我知道如果你有任何问题

oops最初使用的是“9999”而不是“9999”——已修复

#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;
}
输出:

$ 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
$ /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

从文件中读取数组的方法有多种。您的挑战增加了一个简单的复杂性,即必须从文件中读取字符和整数,然后根据字符是否表示数字或是否是单个字符“x”替换值“9”,将元素添加到数组中9999'

最简单的方法是使用面向行的输入从数据文件中一行一行地读取数据,然后根据需要解析每一行。我建议您与
getline
交朋友,以满足所有行输入需求。与
fgets
scanf
相比,它提供了许多好处,并且不需要更多的努力韩不是其他人

从输入中读取数据行后,需要将该行拆分为单词。
strtok
是首选工具,否则可以编写自定义解析器(取决于您的