#include<stdio.h>
int main(void) {
char line[81],character;
int c;
c=0;
printf("Enter Text.Press <Return> at end \n");
do{
character=getchar();
line[c]=character;
c++;
}while(character !='\n');
c=c-1;
line[c]='\0';
printf("\n%s\n",line);
}

- 71,951
- 46
- 188
- 305

- 11
- 6
-
you might need to read about [what is a newline character -- '\n'](https://stackoverflow.com/questions/3267311/what-is-newline-character-n) – ad absurdum Mar 14 '20 at 19:21
-
You'll run into problems if you encounter EOF before you get a newline — which is possible, though not common. – Jonathan Leffler Mar 14 '20 at 19:40
-
@SaifBashar If some of the answers below has helped you out, don´t forget to accept one or ask for more details if you did not understand it yet. – RobertS supports Monica Cellio Mar 18 '20 at 15:28
2 Answers
The '\n'
is a new line character, as I am sure you allready know. New line is a character like anyone else, for example 'a'
,'b'
,'c'
,'\t'
(tab), a space ' '
etc.
So while(character !='\n')
means as long the character is not a newline.

- 4,048
- 2
- 21
- 45
\n
is the newline character, made by the press to Enter/Return.
With
do{
...
}while(character !='\n');
you have a do-while
loop with a condition to proof if the character in character
is a newline which is appended after the proper input. The loop breaks if \n
is inside character
and makes no further iterations.
Note that since it is a do-while
loop, the loop´s body got at least one time walk through.
The concept of
do{
character=getchar();
line[c]=character;
c++;
}while(character !='\n');
is to read a character at each walkthrough and to write the characters subsequent into the elements of the array line
, including the newline character.
Note that the appending of \0
after the loop
c=c-1;
line[c]='\0';
is important since this character terminates a proper string!
Also note that the return value of getchar()
is of type int
to hold the erroneous EOF
. You should change the type of character
to int
and later proof this value to make sure no error has occurred, which is important. The assignment to the array is no problem with an object of the type int
since char
is relative to int
.

- 14,524
- 7
- 33
- 80