Q.1)Write a program to display user details as User name,Email,Contact no,Address each on new line.
#include<stdio.h>
#include<conio.h>
void main(){
char username[25],Email[40],contact[15],add[80];
clrscr();//to be used after
printf("Enter all your details below\n");
*//gets() function does not work after the scanf() function.
//i.e gets() should be written on top after declaration to work.*
printf("username :");
scanf("%s",&username[0]);
printf("Enter your Address:");
gets(add); // **←---------------------------------------GETS( ) inserted after scanf()**
printf("Email ID :");
scanf("%s",Email);
printf("Contact :");
scanf("%s",contact);
printf("\nYour username is %s\n",username);
printf("Your Email ID is %s\n",Email);
printf("Your Contact No. is %s\n",contact);
printf("Your Address is %s\n",add);
getch();
}
gets() function is not taking any input from the user; once it is used after scanf() function.
1.I don't know why gets function is behaving in this manner?? 2.Same happens with scanf("%c")[format specifier for char] when its is used after scanf("%s")[format specifier of string]
void main()
C++ has never permitted void main(), though some compilers might permit it either as an extension or just because they don't diagnose it.Similarly C has never permitted void main()
other than as an extension; the same 1989 standard that introduced the void keyword.There is no particular advantage in being able to write void main()
rather than int main()
. You don't even need to explicitly return a value; falling off the end of main is equivalent to return 0; (in C++, and in C starting with C99).
gets()
The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.so,use scanf("%[^\n]s", name);
instead of gets(name);
.
<conio.h>
is a C header file used mostly by MS-DOS compilers to provide console input/output. It is not part of the C standard library or ISO C, nor is it defined by POSIX.so, try use some other compilers.
here is the working version
#include<stdio.h>
#include<string.h>
int main(){
char username[25],Email[40],contact[15],add[80];
//to be used after
printf("Enter all your details below\n");
//gets() function does not work after the scanf() function.
//i.e gets() should be written on top after declaration to work.*
printf("username :");
scanf("%[^\r\n]s",username);
getchar();
printf("Enter your Address:");
scanf("%[^\n]s", add);
printf("Email ID :");
scanf("%s",Email);
printf("Contact :");
scanf("%s",contact);
printf("\nYour username is '%s'\n",username);
printf("Your Email ID is '%s'\n",Email);
printf("Your Contact No. is '%s'\n",contact);
printf("Your Address is '%s'\n",add);
return 0;
}
the address is taking a newline character from the username statement.so, to print the address properly i used the getchar()
function,which detected the newline character before the address taken the input.