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. :)
You can read an entire line using getchar() as illustrated in the answer to this question: getchar() and reading line by line
This is a non-trivial question. Here's some C code which will read a table in, subject to some limitations in line length and 10 rows maximum. There's also very little error checking. Each row is stored as one string, a line. You will have to parse the string for each row later in a loop to find each column's value. You might use strtok() or a regex() ("man 3 regex") to do that.
#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
}
}