Advertisement
CherMi

Lab 8 final version

Nov 8th, 2019
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <locale.h>
  4.  
  5. int string_length(char *s);
  6.  
  7. void main()
  8. {
  9.     setloclale(LC_ALL, "RUSSIAN");
  10.     char s[256];
  11.     char max_string[256];
  12.     int string_counter;
  13.     int max_length;
  14.     int current_length;
  15.     int i;
  16.     int flag_enter; //1 - кончается на \n, 0 - не кончается на \n;
  17.     FILE *in;
  18.     in = fopen("C:\\test\\file.txt", "rt");
  19.     if (in != NULL)
  20.     {
  21.         string_counter = 0;
  22.         max_length = -1;
  23.         while (fgets(s, 256, in) != NULL)
  24.         {
  25.             flag_enter = 0;
  26.             string_counter++;
  27.             current_length = string_length(s);
  28.             if (current_length > max_length)
  29.             {
  30.                 max_length = current_length;
  31.                 for (i = 0; i <= max_length; i++)
  32.                 {
  33.                     if (s[i] != '\n') { //символ '\n' запишем как '\0'
  34.                         max_string[i] = s[i];
  35.                     }
  36.                     else {
  37.                         max_string[i] = '\0';
  38.                         flag_enter = 1;
  39.                     }
  40.                 }
  41.  
  42.             }
  43.             else
  44.             {
  45.                 for (i = 0; i <= current_length; i++)
  46.                 {
  47.                     if (s[i] == '\n')
  48.                     {
  49.                         flag_enter = 1;
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.         if (feof(in) == 0)
  55.         {
  56.             printf("An error occured.");
  57.         }
  58.         else if ((string_counter == 0))
  59.         {
  60.             printf("This file is empty");
  61.         }
  62.         else
  63.         {
  64.             if (flag_enter == 1) //Если последняя строка пустая
  65.                 string_counter++;
  66.             printf("String count = %d\n", string_counter);
  67.             printf("The longest string: \n\"%s\"", max_string);
  68.             printf("\nLength of the longest string = %d\n", max_length);
  69.         }
  70.         fclose(in);
  71.     }
  72.     else
  73.     {
  74.         printf("Cannot open file.");
  75.     }
  76. }
  77. int string_length(char *s)
  78. {
  79.     int i = 0; //Длина строки
  80.     char symb = *(s);
  81.     while ((symb != '\n') && (symb != '\0'))
  82.     {
  83.         i++;
  84.         symb = *(s + i);
  85.     }
  86.     return i;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement