in how many ways can you accept data in a string?
Answers
Answer:
We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds first space.
There are 3 method by which C program accepts string with space in the form of user input.
Let we have a character array (string) named as str[]. So, we have declared a variable as char
#include <std
Note : gets() has been removed from c11. So it might give you a warning when implemented.
We see here that it doesn’t bothers about size of array. So, there is chance of Buffer Overflow.
Method 2 : To overcome above limitation, we can use fgets as :
Syntax : char *fgets(char *str, int size, FILE *stream)
Method 3 : Using %[^\n]%*c inside scanf
Explanation : Here, [] is the scanset character. ^\n tells to take input until newline doesn’t get encountered. Then, with this %*c, it reads newline character and here used * indicates that this newline character is discarded.
Answer:
The null character '0' terminates a string, which is a sequence of characters treated as a single data item. A string is a character array that is one-dimensional.
Explanation:
A string is a character array that is one-dimensional. Arrays of characters are used to represent strings.
The null character, which is simply the character with the value 0, is used to indicate the end of the string.
In C, we can use scanf(“%s”, str) to take string input. However, it only accepts string until the first space is found. The C program accepts a string with space in the form of user input via four methods. Let's start with a character array (string) named str[]. As a result, char str[20] has been declared as a variable.
Method 1: Is to use the gets:
Syntax : char *gets(char *str)
Method 2: To get around the above restriction, we can use fgets as follows:
char *Syntax : char *fgets(char *str, int size, FILE *stream)
Method 3: Inside scanf, Using %[^\n]%*c.
Method 4: Inside scanf, Using %[^\n]s .