xxxxxxxxxx
// C Code to explain why adding
// "while ( (getchar()) != '\n');"
// after "scanf()" statement
// flushes the input buffer
#include<stdio.h>
int main()
{
char str[80], ch;
// scan input from user -
// GeeksforGeeks for example
scanf("%s", str);
// flushes the standard input
// (clears the input buffer)
while ((getchar()) != '\n'); //without this it wouldn't write 'a' as an output
// scan character from user -
// 'a' for example
ch = getchar();
// Printing character array,
// prints “GeeksforGeeks”)
printf("%s\n", str);
// Printing character a: It
// will print 'a' this time
printf("%c", ch);
return 0;
}
/*
Input:
GeeksforGeeks
a
Output:
GeeksforGeeks
a
*/
xxxxxxxxxx
#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
//declaring character pointer
char *buffer;
//allocating memory at run time
buffer = (char*)malloc(MAX*sizeof(char));
if(buffer==NULL)
{
printf("Error in allocating memory!!!\n");
return -1;
}
//assign any string
strcpy(buffer,"Hello, World");
//printing
printf("buffer: %s", buffer);
//freeing memory
free(buffer);
return 0;
}
xxxxxxxxxx
#define MY_BUFFER_SIZE 1024
char mybuffer[MY_BUFFER_SIZE];
int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);