2013-07-09 48 views
0

我使用數組來表示一個表,我想使用「getchar」來更新表中的值。使用「getchar」更新數組中的值

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); 

    } 

我的想法是,我應該創建一個表,並將所有值設置爲零的輸入表第一。然後基於getchar()更改它。最後,更新原始表格。但是,我不知道如何使用getchar來更改值。有人可以幫我嗎?如果有什麼讓你感到困惑,留下評論。預先感謝。 :)

+1

'getchar()'不會改變'stdin'後面的緩衝區。它只是*獲得*一個字符。 – Kninnug

+0

@Kninnug我想使用getchar()存儲輸入,然後更改值。可能嗎? – user2185071

+0

@ user2185071什麼阻止了您更改值? – DzungAh

回答

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 
    } 
}