在不知道行长的情况下将行从标准输入读入 C 中的二维数组

Reading lines from stdin into 2d array in C without knowing length of lines

我想从 stdin 读取可变长度的行,直到输入结束。示例输入将是这样的:

#.###############
#...#...........#
#.###.#####.#.###
#...........#...#
###############.#

但行和列的长度各不相同。

除了将其作为字符读取外,将其读入二维数组的最佳方法是什么?

假设您 运行 在 POSIX 兼容系统上,您可以使用 the getline() function 读取几乎任意长度的行(仅受可用内存限制)。这样的事情应该有效:

char *line = NULL;
size_t bytes = 0UL;

for ( int ii = 0;; ii++ )
{
    ssize_t bytesRead = getline( &line, &bytes, stdin );
    if ( bytesRead <= 0L )
    {
        break;
    }

    lineArray[ ii ] = strdup( line );
}

free( line );

您必须添加错误检查并lineArray 自己处理。

char *buff = malloc(1024 * 100); // 100K should be plenty, tweak as desired.
char *maze = 0;
int width = 0, 
int height = 0;    

FILE *fp = fopen(input.txt, "r");
fgets(buff, 1024 * 100, fp);
if(!strchr(buff, '\n'))
   goto failed_sanity_test;
striptrailingwhitespace(buff);
if(height == 0)
   width = strlen(buff);
/* sanity-test width ? */
else
   if(strlen(buff) != width)
       goto ragged_edge_maze;
temp = realloc(maze, width * (height + 1));
if(!temp) 
  goto out_of_memory;
maze = temp;
memcpy(maze + height * width, buff, width);
height++;

与许多其他语言相比,它在 C 中很繁琐,但至少您可以完全控制错误条件。