Advertisement
xeritt

Чтение scanf массива строк с пробелами

Mar 27th, 2019
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. char *scan_line(char *buffer, int buffer_size)
  5. {
  6.     char *p = buffer;
  7.     int count = 0;
  8.     do {
  9.         char c;
  10.         scanf("%c", &c);    // scan a single character
  11.         // break on end of line, string terminating NUL, or end of file
  12.         if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
  13.             *p = 0;
  14.             break;
  15.         }
  16.         *p++ = c;   // add the valid character into the buffer
  17.         count++;
  18.     } while (count < buffer_size - 1);  // don't overrun the buffer
  19.     // ensure the string is null terminated
  20.     buffer[buffer_size - 1] = 0;
  21.     return buffer;
  22. }
  23.  
  24. char **scan(char **mas, int n, int len)
  25. {
  26.     mas = (char **)malloc(n * sizeof (char *)); // выделение памяти под массив указателей
  27.     for (int i = 0; i < n; i++) {
  28.         mas[i] = (char *)malloc(len * sizeof (char) + 1);   // выделение памяти под cтроку
  29.         scan_line(mas[i], len);
  30.     }
  31.     return mas;
  32. }
  33.  
  34. void print(char **mas, int n, int m)
  35. {
  36.     printf("Массив значений:\n");
  37.     for (int i = 0; i < n; i++) {
  38.         printf("%s\n", mas[i]);
  39.     }
  40.  
  41. }
  42.  
  43. int main()
  44. {
  45.     int n, len;
  46.  
  47.     printf("Введите число строк:");
  48.     scanf("%d", &n);
  49.  
  50.     printf("Введите длину строк:");
  51.     scanf("%d", &len);
  52.     char buf[len];
  53.     scan_line(buf, 2);  //считываем перенос строки
  54.  
  55.     char **mas = 0;
  56.     mas = scan(mas, n, len);
  57.     print(mas, n, len);
  58.  
  59.     for (int i = 0; i < n; i++) {
  60.         free(mas[i]);
  61.     }
  62.     free(mas);
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement