c - ANSI C - 数字矩阵的输入

标签 c input matrix

我必须实现一个 C 程序来执行两个矩阵的乘法(是的,家庭作业:),并且我正在尝试设计一个函数来接收用户的输入并验证它。

我最初的想法是:让我们只要求用户输入矩阵(数字用空格分隔,行用换行符分隔,换行符后面可能有一个“e”来表示矩阵结束),以便程序会自动计算列数和行数并将它们存储在二维数组中。但是,如果我事先不知道它们的大小,如何动态地为它们分配足够的内存?如果可能的话,我会避免要求用户手动输入每个矩阵的行数和列数。

此外,验证输入是否存在错误和/或丢失数据(例如字母、垃圾、数字少于其他行等)的最佳方法是什么?我正在考虑对每一行进行 strtok,使用空格作为分隔符来分割它们,并检查每个标记是否严格是数字。这是确定每行是否只包含有效数值的最佳方法吗?有没有更干净、更理智的方法?

这是我的伪代码:

function getMatrix () {
   while(true) {
   Receive a matrix as input, until the user enters 'e' in a new line by itself;
   Split the matrix in rows delimited by newlines;
   Split the rows in strings delimited by whitespaces;
   For each string {
     If the string is numeric, save it as matrix[rowNumber][colNumber];
     Else print a warning and discard the entire input;
   }
   If each row of the matrix has an equal number of elements {
      return the matrix as an array of integers;
   } else {
      print a warning and let the user re-enter the data.
  }
 }
}

main () {
    matrix1 = getMatrix;
    matrix2 = getMatrix;

    matrix1x2 = multiply the two matrices (this is the easy part :)
    print matrix1x2.
}

最佳答案

这在 C 中有点麻烦。但是如果您不希望用户指定矩阵的维度,则需要一个不断增长的缓冲区来放入数字。您可以使用 realloc 来实现这一点。它会像这样(未测试):

int n = 0, nmax = 100;
size_t len = 0;
int nrow = 0, ncol = 0;
double * mat = malloc(nmax);
char * line = NULL, *tok;
while(getline(&line, &len, stdin) > 0)
{
    nrow++;
    ncol = 0;
    for(tok = strtok(line, " \t"); tok; tok = strtok(NULL, " \t"))
    {
        ncol++; n++;
        if(n > nmax) mat = realloc(mat, (nmax *= 2)*sizeof(double));
        mat[n-1] = atof(tok);
    }
}
mat = realloc(mat, nrol*nrow*sizeof(double));
free(line);

它的作用是逐行读取输入,循环遍历空格或制表符分隔的标记,将每个标记转换为 double 型,并将其分配给一维缓冲区,该缓冲区根据需要进行扩展。我每次将其容量乘以两倍,以最大限度地减少重新分配内存所花费的时间(这也是 C++ vector 类所做的)。它还跟踪所看到的行数和列数,但不进行任何错误检查,因此实际版本需要更多工作。

要获取结果矩阵索引 (i,j) 处的值,您必须计算线性索引:val = mat[i*ncol+j]

关于c - ANSI C - 数字矩阵的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129577/

相关文章:

python - 如何使进程能够写入主程序的数组?

c - linux 驱动程序间通信

c - 什么是重入程序?

javascript - 如果有多个位置,如何寻址一个位置的两个 INPUT 的值

javascript - 使用 javascript 禁用输入文本类型

matlab - 根据两行从矩阵中提取元素并获取它们的平均值

c - 有没有办法通过输入学生 ID 来删除文本文件中的记录?

c - 通过 socketCAN 发送 EFF 29 位 ID 消息的问题

html - 使用 -webkit-search-cancel-button 时真正隐藏的清除图标

c++ - 用于在 C/C++ 中实现二维数组的数据局部性