How to accept strings and print then them please explain me with example if possible
Thanks in advance
.............
How to accept strings and print then them please explain me with example if possible
Thanks in advance
.............
int main()
{
char p[25];
printf("Hello world!\n");
scanf("%s",p);
printf("%s\n",p);
return 0;
}
Or
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *p=NULL;
p=malloc(10);
printf("Hello world!\n");
scanf("%s",p);
printf("%s\n",p);
return 0;
}
Or
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *p=NULL;
p=malloc(10);
printf("Hello world!\n");
gets(p);
printf("%s\n",p);
return 0;
}
It's somewhat amusing how you managed to pick the two worst possible options. gets() is completely unsafe, and the latest C standard actually removed it from the library. scanf()'s "%s" specifier without a field width is no better than gets(). In both cases input longer than the memory can hold will cause buffer overflow. They also do different things in that gets() reads a whole line while scanf("%s"...)
only reads up to the nearest whitespace.
The recommended go to solution is fgets():
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[BUFSIZ];
printf("Enter a string: ");
fflush(stdout);
if (fgets(buf, sizeof buf, stdin)) {
buf[strcspn(buf, "\n")] = '\0'; // Optionally remove any newline character
printf("'%s'\n", buf);
}
return 0;
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.