2016-11-22 3 views
-1

Я пытаюсь создать программу, в которой пользователь сначала вводит размер матрицы, а затем будет ли каждая ячейка занята (o) или незанятой (.). Как бы написать его так, чтобы пользователь вводил целую строку входов для занятых/незанятых, а не по ячейкам, используя вложенные для циклов?C - Пользовательский ввод в матрицу

UPDATE

Существует пример, когда элементы вводятся по одному:

#include <stdio.h> 

#define MAX_SIZE 100 

int main(void) 
{ 
    char matrix[MAX_SIZE][MAX_SIZE] = { 0 }; 
    int rows = 0, cols = 0; 
    while (rows < 1 || rows > MAX_SIZE) 
    { 
     printf("What is the number of rows? "); 
     scanf("%d", &rows); 
    } 
    while (cols < 1 || cols > MAX_SIZE) 
    { 
     printf("What is the number of columns? "); 
     scanf("%d", &cols); 
    } 
    // fill the matrix 
    printf("Please, fill the matrix by entering o for occupied or . for unoccupied cell (E for exit)\n"); 
    int r, c, ch; 
    int fulfill = 1; 
    for (r = 0; r < rows && fulfill; r++) 
    { 
     for (c = 0; c < cols && fulfill; c++) 
     { 
      // clean the input bufer 
      while ((ch = getchar()) != '\n' && ch != EOF); 
      // read data 
      printf("cell [%d, %d] : ", r + 1, c + 1); // or just r, c if you prefer 0..(N-1) indexing 
      while (matrix[r][c] != 'o' && matrix[r][c] != '.' && matrix[r][c] != 'E') 
      { 
       scanf("%c", &matrix[r][c]); 
      } 
      if (matrix[r][c] == 'E') 
      { 
       fulfill = 0; 
      } 
     } 
    } 
    // output 
    printf("\nResult is:\n"); 
    for (r = 0; r < rows; r++) 
    { 
     for (c = 0; c < cols; c++) 
     { 
      printf("%c", matrix[r][c]); 
     } 
     printf("\n"); 
    } 
} 
+1

Добро пожаловать в переполнение стека! Покажите свои исследования/отладки. Сначала прочитайте страницу [Ask]. –

ответ

1

Рассмотрим следующий пример:

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

int main(void) 
{ 
    char** matrix; // now it is a pointer and memory will be allocated after getting values of rows and columns 
    int rows = 0, cols = 0; 
    while (rows < 1) 
    { 
     printf("What is the number of rows (should be >= 1)? "); 
     scanf("%d", &rows); 
    } 
    while (cols < 1) 
    { 
     printf("What is the number of columns (should be >= 1)? "); 
     scanf("%d", &cols); 
    } 
    // part 1 for memory allocation 
    matrix = (char**)malloc(sizeof(char*) * rows); 
    // fill the matrix 
    printf("Please, fill the matrix by entering o for occupied or . for unoccupied cell (other chars will be ignored)\n"); 
    int r, c, ch; 
    for (r = 0; r < rows; r++) 
    { 
     // part 2 for memory allocation - memory for each row 
     matrix[r] = (char*)malloc(sizeof(char) * cols); 
     for (c = 0; c < cols; c++) 
     { 
      // read while apropriate character was found 
      while ((ch = getchar()) != 'o' && ch != '.'); 
      // save character to matrix 
      matrix[r][c] = ch; 
     } 
    } 
    // output 
    printf("\nResult is:\n"); 
    for (r = 0; r < rows; r++) 
    { 
     for (c = 0; c < cols; c++) 
     { 
      printf("%c", matrix[r][c]); 
     } 
     printf("\n"); 
    } 
    // free the memory 
    for (r = 0; r < rows; r++) 
    { 
     free(matrix[r]); 
    } 
    free(matrix); 
} 

Здесь данные хранятся в куче (динамическую память, выделять на malloc или другие подобные функции) и, несмотря на использование тех же вложенных циклов, входящих в i разные. Смотрите, как это работает:

What is the number of rows (should be >= 1)? 3 
What is the number of columns (should be >= 1)? 3 
Please, fill the matrix by entering o for occupied or . for unoccupied cell (other chars will be ignored) 
o.o 
.o. 
o.o 

Result is: 
o.o 
.o. 
o.o 

Пользователь может ввести построчно с помощью Enter клавишу, чтобы начать новую строку, или просто введите o и . по одному для всех ячеек (заполнение будет строка за строкой в ​​любом случае) , Ненужные элементы, а также несоответствующие символы (отличные от o и .) будут проигнорированы. Например:

What is the number of rows (should be >= 1)? 4 
What is the number of columns (should be >= 1)? 5 
Please, fill the matrix by entering o for occupied or . for unoccupied cell (other chars will be ignored) 
ooZooCooXooOoo 
...... 
........XXX 

Result is: 
ooooo 
ooooo 
..... 
..... 
+0

Привет, может ли статическое распределение быть жизнеспособным вариантом? Также мой код предполагает, что пользователь вводит правильный ввод (количество и правильные символы), так как это изменит пример? Я новичок в C и задавался вопросом, можно ли упростить код. – Zhasan

+0

Я добавил пример на вопрос, где массив статичен. Вы можете использовать тот же подход. Если у вас есть какие-либо вопросы, задайте новый пост после того, как у вас есть код – VolAnd

+0

Даже если пользователь всегда прав, некоторые символы (например, '\ n') должны быть пропущены. Поэтому будьте осторожны с минимизацией кода. И если этот ответ полезен, примите его – VolAnd

Смежные вопросы