Advertisement
Balda

Выравнивание

Oct 19th, 2014
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.36 KB | None | 0 0
  1. /*Произвести выравнивание по правому краю введенного текста, для чего к каждой строке применить функцию WIDE(str,k), которая равномерно вставляет пробелы между словами так, чтобы длина строки str стала равной k. (Величина k должна быть больше длины самой длинной строки текста.)*/
  2.  
  3.  
  4. #pragma warning(disable:4018)
  5. #include <iostream>
  6. #include <Windows.h>
  7. #include <string.h>
  8. using namespace std;
  9.  
  10. void WIDE(char *string, char *replace_string, int size)
  11. {
  12.         unsigned int i, j, k;
  13.         char space[1] = { ' ' };
  14.         int space_counter = 0;
  15.         int need_space;
  16.         int counter = 0;
  17.         int string_length = strlen(string);
  18.         // Считаем пробелы
  19.         for (i = 0; i < string_length; i++)
  20.         {
  21.                 if (string[i] == ' ')
  22.                         space_counter++;
  23.         }
  24.         if (space_counter == 0) space_counter = 1;
  25.         // На каждый пробел - ставим M пробелов
  26.         need_space = (size - string_length) / space_counter + 1;
  27.         for (i = 0, k = 0; i < string_length; i++)
  28.         {
  29.                 if (string[i] != ' ')
  30.                 {
  31.                         replace_string[k] = string[i];
  32.                         k++;
  33.                 }
  34.                 else
  35.                 {
  36.                 for (j = 0; j < need_space; j++)
  37.                         {
  38.                                 if (strlen(replace_string) < size)
  39.                                 {
  40.                                         replace_string[k]=' ';
  41.                                         k++;
  42.                                 }
  43.                         }
  44.                 }
  45.         }
  46.         replace_string[k] = '\0';
  47. }
  48.  
  49. int main()
  50. {
  51.         SetConsoleCP(1251);
  52.         SetConsoleOutputCP(1251);
  53.         int k;
  54.         bool flag;
  55.         char string[80] = { 0 }, packed_string[80] = { 0 }, sec_string[80] = { 0 }, replace_string[80] = { 0 };
  56.         cout << "Исходная строка: ";
  57.         cin.getline(sec_string, 80);
  58.         cout << "Выравнивание: ";
  59.         cin >> k;
  60.         WIDE(sec_string, replace_string, k);
  61.         cout << replace_string << endl;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement