问题描述
我正在学习从K&放C; R的的书。我做在书指定的练习。我在练习数1.16,但我不明白。
1.16练习:
My questions:
"...as much as possible of the text..." - is there some limitation on string length? Maybe in standard headers there's a variable with the max allowed value of string length?
"...the length of arbitrarily long input lines..." - but in the code MAXLINE is defined as 1000. It is limited size too. I see some solutions here, but in my opinion it is not solution decision, since on the former there is a restriction on length of a line (1000 characters).
Maybe I don't understood the task. My understanding is I must remove the 1000-character limitation.
It's a pretty early exercise in K&R, you're just supposed to do some minor changes to the code, not a total redesign of the code.
is up to you to interpret. I'd do it by printing what's stored in the
longest
buffer. i.e. print out up to 1000 characters of the line. Again, it's an early exercise, with little introduction to dynamically allocated memory yet. And at the time K&R was written, storing away arbitrarily long text lines wasn't as feasible as it is today.Is a hard requirement. You're supposed to find the correct length no matter how long it is (at least within the bounds of an
int
. )
One way to solve this problem is:
- After the call to getline(), check if the last character read into the
line
buffer is a newline ('\n') - If it is, you read a complete line. The
len
variable is the correct length of the line(the return value of getline(), and no special consideration is needed compared to to original code. - If it is not , you did not read the entire line, and need to hunt for the end of this line. You add a while loop, calling getchar() until it returns a newline (or EOF), and count the number of characters you read in that loop. Just do
len++
to count. - When the while loop is done, the new
len
is now the actual length of the line, but our buffer just has the first 999 characters of it. - As before, you store away (the copy() function call) the current
line
buffer (max 1000 chars) if this line is the longest so far. - When you're done, you print out the stored line as before (the
longest
buffer) and themax
variable for the length.- Due to the above mentioned while loop that
max
length is now correct. - If the
longest
line indeed was longer than 1000 chars. you at least print out those first 999 chars - which is "as much as possible".
- Due to the above mentioned while loop that
I'll not spoil it and post the code you need to accomplish this, but it is just 6 lines of code that you need to add to the longest-line program of exercise 1-16.
这篇关于K&安培; R练习1.16 - 线长度限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!