将.txt文件读入二维数组 [英] Reading a .txt file into a 2-d array

查看:89
本文介绍了将.txt文件读入二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,如下所示:

I have a text file as follows:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20

我想读入一个二维的整数数组.问题是该文件没有提供有关二维数据尺寸的信息.我尝试这样做如下:

I want to read into a 2-d array of integers. The problem is the file provides no information about the dimensions of the 2-d data. I tried doing it as follows:

FILE *input_file = fopen(argv[1], "r");
while (! feof(input_file)) {
    read = fscanf(input_file, "%d%c", &x, &del);
    if (read != 2) {
        i--;
        break;
    }
    in_data[i][j] = x;
    if ( del == '\n') {
        i++;
        j =0;
        continue;
    }
    j++;
}

如果一行中最后一个数据项之后的字符是换行符,则此代码可以正常工作,否则失败.在不事先知道数据尺寸的情况下,从文件中读取二维数据的可靠方法是什么?

This code works fine if the character after the last data-item in a line is a newline, but fails otherwise. What is the reliable way to read 2-d data from a file without knowing the dimensions of the data beforehand?

推荐答案

一种简单的方法是使用fgets一次读取一行.然后,您可以使用strtol读出值.利用它设置的endptr指针,以便您可以读取下一个值.

A simple approach is to use fgets to read a line at a time. You can then use strtol to read the values out. Make use of the endptr pointer it sets so you can read the next value.

或者,您也可以通过一次读取一个字符来使之具有使用空白的简短功能.您可以在那里处理换行符.阅读直到遇到非空白,然后使用ungetc将该字符放回流中.像这样:

Alternatively you can make a short function to eat whitespace by reading a character at a time. You can handle newlines in there. Read until you encounter a non-whitespace and then put that character back into the stream using ungetc. Something like this:

// Returns false if EOF or error encountered.
int eat_whitespace( FILE *fp, int *bNewLineEncountered )
{
    int c;
    *bNewLineEncountered = 0;

    while( EOF != (c = fgetc(fp)) ) {
        if( c == '\n' ) {
            *bNewLineEncountered = 1;
        } else if( !isspace(c) ) {
            ungetc(c, fp);
            break;
        }
    }

    return (c != EOF);
}

这篇关于将.txt文件读入二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆