String Input in C

If you want to read a string into a program, you must first set aside space to store the string and then use an input function to fetch the string.
Creating Space
The first order of business is setting up a place to put the string after it is read. As mentioned earlier, this means you need to allocate enough storage to hold whatever strings you expect to read. Don’t expect the computer to count the string length as it is read and then allot space for it. The computer won’t (unless you write a function to do so). For example, suppose you try something like this:

char *name;
scanf("%s", name);

It will probably get by the compiler, but when the name is read, the name might be written over data or code in your program, and it might cause a program abort. That’s because scanf() copies information to the address given by the argument, and in this case, the argument is an uninitialized pointer; name might point anywhere. Most programmers regard this as highly humorous, but only in other people’s programs.
The simplest course is to include an explicit array size in the declaration:

char name[81];

After you have set aside space for the string, you can read the string. The C library supplies a trio of functions that can read strings: scanf(), gets(), and fgets(). The most commonly used one is gets(), which we discuss first.

The gets() Function

The gets() (get string) function is very handy for interactive programs. It gets a string from your system’s standard input device, normally your keyboard. Because a string has no predetermined length, gets() needs a way to know when to stop. Its method is to read characters until it reaches a newline (\n) character, which you generate by pressing the Enter key. It takes all the characters up to (but not including) the newline, tacks on a null character (\0), and gives the string to the calling program. The newline character itself is read and discarded so that the next read begins at the start of the next line. Following program shows a simple means of using gets().

#include <stdio.h>
#define MAX 81

int main()
    char name[MAX];  /* allot space                  */
    printf("Hi, what's your name?\n");
    gets(name);      /* place string into name array */
    printf("Nice name, %s.\n", name);
    return 0;

You may also like...