How to Read a String in C

By Techwalla Computers Editor

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.

Things You'll Need

  • C/C++ IDE or C compiler
  • Book on C, such as "The C Programming Language" by Brian W. Kernighan

Step 1

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 2

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

#include < stdio.h >

Step 3

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

Step 4

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

Step 5

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

Step 6

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

Step 7

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

Tips & Warnings

  • To learn more about the functions mentioned, visit the C Plus Plus website.
  • Don't try to compile this code. It's only meant to demonstrate the functions. It isn't a coherent program and will give errors when compiled.