Stolar228

Untitled

Sep 8th, 2022
837
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1.  
  2. /*
  3.   си строка
  4.   1 функция - maxlen длина строки
  5.   2 функция - mycopy ( mycopy(a, b), где a - с какого, b - сколько)
  6. */
  7.  
  8. #define _CRT_SECURE_NO_WARNINGS
  9.  
  10. #include <iostream>
  11. using namespace std;
  12.  
  13. #include <cmath>
  14. #include <time.h>
  15.  
  16.  
  17. #define NUMS_CHAR_LEN 10
  18.  
  19. // ввод строки
  20. char *get_string(int *len) {
  21.     *len = 0;
  22.     int capacity = 1;
  23.     char *s = (char*) malloc(sizeof(char));
  24.     char c = getchar();
  25.     while (c != '\n') {
  26.         s[(*len)++] = c;
  27.         if (*len >= capacity) {
  28.             capacity += 1;
  29.             s = (char*) realloc(s, capacity * sizeof(char));
  30.         }
  31.         c = getchar();
  32.     }
  33.     s[*len] = '\0';
  34.     return s;
  35. }
  36.  
  37. // узнать длинну строки
  38. int maxlen(char* str) {
  39.   int i = 0;
  40.   while (true) {
  41.     if (str[i] == '\0') return i;
  42.  
  43.     i++;
  44.  
  45.   }
  46. }
  47.  
  48. // вырезать часть строки
  49. char* mycopy(char* str, int a, int b) {
  50.   char *s = (char*) malloc((b - a) * sizeof(char));
  51.   for (int i = 0; i < (b - a); i++) {
  52.     s[i] = str[a + i];
  53.   }
  54.  
  55.   return s;
  56. }
  57.  
  58. int main() {
  59.     // смена кодировки
  60.   system("chcp 65001"); // можно заменить на setlocale(LC_ALL, "Russian");
  61.  
  62.   int len;
  63.   cout << "Введите строку: ";
  64.   char* str = get_string(&len);
  65.   cout << "Введённая строка: " << str << endl;
  66.   cout << "Длинна строки: " << maxlen(str) << endl;
  67.  
  68.   int a, b;
  69.   // вводим диапазон чисел
  70.   while (true) {
  71.     cout << "A = ";
  72.     scanf("%d", &a);
  73.  
  74.     cout << "B = ";
  75.     scanf("%d", &b);
  76.  
  77.     // проверка
  78.     if (a >= 0 && b <= maxlen(str))
  79.       break;
  80.  
  81.     else
  82.       cout << "Вы вышли за границы строки." << endl;
  83.   }
  84.  
  85.   // вывод вырезанной строки
  86.   cout << "Вырезанная строка: " << mycopy(str, a, b) << endl;
  87.  
  88.     return 0;
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment