0
/*source: stralloc.c*/
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *A;
int max=0;

//need to add error-checking
printf("enter max string length: ");
scanf("%d",&max);
while ((getchar())!='\n');
A=(char *)malloc(max+1); //room for \0
printf("enter string: ");
fgets(A,max,stdin);
printf("Third char is: %c\n",*(A+2));
//printf("Third char is: %c\n",A[2]));
exit(0);
}

I got this code from my class, but there is one part I don't understand. What does while ((getchar())!='\n'); do in this function?

Can anyone explain it to me?

  • 1
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). The `while` loop removes it, otherwise `fgets` will input a blank line. But it is better not to mix your input methods, and not to rely on a future event. One school of thought advises that you use `fgets` for *every* input and you then process the string you get. – Weather Vane Dec 08 '19 at 20:39
  • Which part do you not understand? `while`? `getchar()`? `!=`? `\n`? – mkrieger1 Dec 08 '19 at 20:39
  • @mkrieger1 ```getchar()!=\n``` this part what does it do in this question? – Zhuangzhuang Li Dec 08 '19 at 20:41

2 Answers2

2
while ((getchar())!='\n');

The above line means, it will keep reading from the input stream until newline character '\n' is encountered.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15
2
while ((getchar())!='\n');

Program execution continues at this line until it receives new line character(i.e Enter)'\n'. 'getchar()' method waits until it receives some input from keyboard. Once input is received it is compared with ('\n') if it is not a '\n' it calls getchar() again.

flowchart

Sudhakar Naidu
  • 244
  • 2
  • 7