I
I
IndusDev2017-06-11 11:13:03
Programming
IndusDev, 2017-06-11 11:13:03

What for in this case to register len-1?

Упражнение 1.17. Напишите программу для вывода всех строк входного потока, имеющих длину более 80 символов.

/* программа вывода всех строк входного потока, имеющих длину более 80 символов */

#include "stdafx.h"
#define MAXLINE 1000 /* максимальная длина строки в потоке */

int getline(char line[], int maxline);

int main()
{
int len; /* длина текущей строки */
char line[MAXLINE]; /* текущая введенная строка */

while ((len = getline(line, MAXLINE)) > 0)
/* если количество символов в строке больше 80, выводим эту строку */
===============================================================
if (len - 1 > 80) /* "len - 1" не считаем нулевой символ '\0' */
===============================================================
printf("This string is longer than 80 characters: %s", line);
return 0;
}

/* getline: считывает строку в s, возвращает ее длину */
int getline (char s[], int lim)
{
int c, i;

for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}

Why (len-1) > 80 and not just len ​​> 80. After all, for example, if we enter 123456\n, the getlen function will return len = 7. If we enter len-1, we get 6 characters (But this does not take into account \ n).
But if we simply enter 123456, the function will return len = 6. But len-1 = 5, and there are 6 characters ... Why is this

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Tallmange, 2017-06-11
@p00h

The character '\0' means the end of the line, it is "official" in this case.

1
15432, 2017-06-11
@15432

len-1 is not needed there, getline does not take into account the terminating zero.

On success, getline() and getdelim() return the number of characters
read, including the delimiter character, but not including the
terminating null byte ('\0').

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question