Advertisement
semenrbt

4.2 dinamic

Feb 18th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. char *CreateStr(int N){
  6.     char *mas = NULL;                      
  7.     mas = (char*) malloc(sizeof(char)*N);
  8.     if(mas == NULL) return NULL;
  9.     for(int k = 0; k < N; k++)
  10.         mas[k] = rand()%10 + 48;
  11.     return mas;
  12. }
  13.  
  14.  
  15. int convert(char *str)  // Функция конвертации строки в число
  16. {
  17.   if(str == NULL) return -1;
  18.   int k = 0;
  19.   int count = 0;
  20.   int flag = 0;
  21.   while(str[k] > 13)
  22.   {
  23.     flag = 1; // На случай, если в строке будет 0, чтобы понимать, работал цикл или нет
  24.     if(str[k] < 48 || str[k] > 57) return -1; // Если найдено не число, то ошибка
  25.     count = count*10 + (str[k] - 48); // Формула преобразования в число
  26.     k++; // Переход на следующий элемент строки
  27.   }
  28.   if(count == 0 && flag == 0) return -1; // Если не было найдено чисел
  29.   return count;
  30. }
  31.  
  32.  
  33. int main() {  
  34.   srand(time(NULL));
  35.   const int N = rand()%5 + 1;
  36.   char * Str = CreateStr(N);
  37.   if(Str == NULL){ // Проверка
  38.         printf("Error.\n");
  39.         return 0;
  40.   }
  41.   int a = convert(Str);
  42.   if(a == -1) printf("Error.");
  43.   else printf("%d\n", a);
  44.   free(Str);
  45.   return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement