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.

Step

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.

Step

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

Step

#include < stdio.h >

Step

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

Step

// 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()"

Step

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":

Step

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);

Step

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

Step

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

Step

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

Step

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); }

Step

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

Step

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); }