-4
#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);
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305

2 Answers2

1

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.

Themelis
  • 4,048
  • 2
  • 21
  • 45
1

\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.