How to Read a String in C

How to Read a String in C. The C programming language doesn't provide an actual string data type. In C, a string is emulated by an array of characters that terminates in NULL. Such an array can be declared statically or as a pointer. Standard C provides many functions to manipulate character arrays or C strings. This article focuses on the functions that read from the input stream and from files. Follow these tips to learn how to read a string in C.

Video of the Day


Understand the basics. A C string is an array of type chart. As with all C arrays, the first element is indexed at 0, and the last at "length of string minus 1." Usually, the compiler inserts NULL at the last location, so the string can hold "length of string minus 1" elements. Null is equivalent to 0x00 in integer form and '\0' in char form. Elements are accessed by the "[]" operator. Step 2 illustrates these concepts.


Add the "include directive" below to any source file before using the functions of this tutorial:

#include < stdio.h >


Declare a C string. The code below shows a declaration using the static and the pointer method:

// static declaration char str[50] = {0}; // shorthand way to initialize all elements to 0 // str[49] is NULL // str has capacity for 48 chars // declaration by pointer char pStr = NULL; // no memory allocation pStr = (char)malloc(50); // this is done by "malloc()"


Read data into a C string using "scanf()," which reads a series of strings separated by space from the standard input and places them in the addresses belonging to the appropriate reference variables, according to a "format string":

int n; printf("Enter your First name and Age: "); scanf("%s%d", str, &n); // printf("Your name is %s and you are %d old\n", str, n);


Put data into a C string using the simpler "gets()" function, which reads data from the standard input into a string only:

printf("Enter you Last name: "); gets(str); printf("Your name is %s\n", str);


Read file data into a C string using "fscanf()"; this function is analogous to "scanf()":

FILE* pFile; pFile = fopen("myFile.txt", "r"); // assume the file exists and has data if (NULL != pFile) { fscanf(pFile, "%s", str); printf("The first word in the file is %s\n", str); fclose(pFile); }


Repeat Step 5 using "fgets()," which works the same as "gets()":

FILE* pFile; pFile = fopen("myFile.txt", "r"); if (NULL != pFile) { fgets(pFile, str); printf("The first word in the file is %s\n", str); fclose(pFile); }

Show Comments