E
E
Evgeny Yakushov2018-09-20 21:28:57
C++ / C#
Evgeny Yakushov, 2018-09-20 21:28:57

Where are the extra characters at the end (2 pcs)?

There is a code, there are 2 prints, for clarity of the problem, for some reason a line consisting of 9 characters does not end, but continues to work in the while loop, that is, on the 10th and 11th elements

//Lab 8

#include "stdafx.h"
#include <stdio.h>
#include <locale.h>

int string_research(char *str, int &i, char *word){

  int amount = 0;

  while (str[i] != '\n' && str[i] != '\0' && str[i] != ' ') {
    word[amount] = str[i];
    i++;
    amount++;
  }
  word[amount] = 0;

  return amount;

}

int main() {

  setlocale(LC_ALL, "rus");

  int i = 0, a = 0, b = 0, temp, amount_word = 0, min_length = 32, max_length = 0;
  char str[256], word[32], min_word[32], max_word[32];

  FILE * fp = fopen("input.txt", "r");

  if (fp != NULL) {
    while (fgets(str, 256, fp) != NULL) {

      while (str[i] != '\0') {

        printf("\n\n\n%c\n\n\n\n", str[10]);
        printf("\n\n\n%c\n\n\n\n", str[11]);

        temp = string_research(str, i, word);

        if (temp < min_length) {

          min_length = temp;

          while (word[a]) {
            min_word[a] = word[a];
            a++;
          }
          min_word[a] = 0;

          if (min_length > max_length) {
            while (min_word[b]) {
              max_word[b] = min_word[b];
              b++;
            }
            max_word[a] = 0;
            max_length = min_length;
          }
          amount_word++;

        }else if (temp > max_length) {

          max_length = temp;
          while (word[a]) {
            max_word[a] = word[a];
            a++;
          }
          max_word[a] = 0;
          amount_word++;

        }else if (temp == min_length || temp == max_length) amount_word++;

        a = 0;
        i++;
      }
      i = 0;
    }
  }
  fclose(fp);

  printf("\nКол-во слов = %i\n", amount_word);
  printf("\nМин. длина = %i\n", min_length);
  printf("Слово: %s\n", min_word);
  printf("\nМакс. длина = %i\n", max_length);
  printf("Слово: %s\n", max_word);

  getchar();
  return 0;
}

It turns out the error
5ba3e63276847084790071.png
A should be:
'min. length' = 3
'Word': red
ref. the file looks like this:
5ba3e6d442d89440635087.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-09-20
@yevgenyyakushov

string_research terminates at character '\0', leaving i with the index of that character. But at the end of the loop is while (str[i] != '\0'), i++which advances i beyond the end of the string. To make it work, you can fix it i++withif (str[i]) i++;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question