0

I use a array to represent a table and I want to use "getchar" to update the value in the table.

 Original table:  0 0 0 0     Input table: 1 0   Output table: 1 0 0 0
                  0 0 0 0                  1 1                 1 1 0 0
                  0 0 0 0                                      0 0 0 0

struct dimension {// represent the number of row and number of col of a table
  int num_row;
  int num_col;
};

void set_value(int t[], 
         const struct dimension *dim,
         const int row, 
         const int col, 
         const int v) {
         t[row*dim->num_col+col] = v;
 }//update the value in a table

    void update (int t[], 
          const struct dimension *table_dim,
          struct dimension *input_dim) {
          for (int k=0; k<(input_dim->num_row); k++){
             for (int l=0; l<(input_dim->num_col); l++){
              array[l] = getchar();
              table_set_entry(array, input_dim, 0, 0,array[l]);
              if (array[l] == '\n') break;
             }
           }

 }

   int main(void) {
         int o[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
         const struct dimension a = {3,4};
         struct dimension in_dim = { 4, 5 };
         update(o,a,in_dim);

  } 

My idea is that I should create a table and set all the value to be zero for input table first. Then change it base on the getchar(). At last, update the original table. However, I dont know how to use getchar to change the value. Can someone help me out? If there is something makes you confuse, leave a comment. Thank in advance. :)

4

1 回答 1

0

您可以使用 getchar() 读取整行,如该问题的答案所示: getchar() and reading line by line

这是一个不平凡的问题。这是一些将读取表格的 C 代码,但受行长度和最大 10 行的限制。错误检查也很少。每行存储为一个字符串,一行。您必须稍后在循环中解析每一行的字符串以找到每一列的值。您可以使用 strtok() 或 regex() (“man 3 regex”)来做到这一点。

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>

#define MAXLINE 1024
#define MAXROWS 10

int
main() {
    int inRows = 0;
    int inCols = 0;
    int i;
    int c;
    int line_length = 0;

    char rows[MAXROWS][MAXLINE];

    printf("How many rows in the input table?  ");
    scanf("%d", &inRows);
    getchar();  // get and throw away newline
    printf("How many columns in the input table?  ");
    scanf("%d", &inCols);
    getchar();  // get and throw away newline

    if (inRows < 1 || inCols < 1 || inRows > MAXROWS) {
        printf("Table dimensions of %d rows by %d cols not valid.\n", inRows, inCols);
        exit(1);
    }

    // read inRows lines of inCols each.
    for (i = 0; i < inRows; i++) {
        printf("Input table data for row #%d in the format col1 col2...\n", i);
        while ((c = getchar()) != '\n' && line_length < MAXLINE - 1) {
            rows[i][line_length++] = c;
        }
        rows[i][line_length] = 0;   // nul terminate the line
    }
}
于 2013-07-09T02:15:54.400 回答