scanf() vs gets() Function to Read String in C

Get Certified in C Programming for Free and Take Your Skills to the Next Level

Being able to read string input efficiently is crucial for many C programs. The C programming language provides several functions that allow us to read string data from the user or other sources.

In this post, we will examine the two widely used C methods scanf() and gets(), for reading strings. The scanf() and gets() functions work quite differently for reading strings in C. Understanding the key differences between the two will help us pick the right one for our specific use case and avoid potential issues like buffer overflows.

The scanf() Function in C for Reading Strings

In C programming, formatted input is read from the standard input stream stdin using the scanf() method. We employ the%s format specifier when using scanf() to read strings.

Here is a simple example to demonstrate reading a string from the user using scanf():

#include <stdio.h>

int main() {

  char name[50];

  printf("Enter your name: ");
  scanf("%49s", name);

  printf("Your name is: %s", name);
  
  return 0;
}

Output:
Enter your name: Rohan
Your name is: Rohan

When executed, this program waits for the user to enter a string value, which is then stored in the name character array. The %s format specifier instructs scanf() to interpret the input as string data.

Some key points to note about using scanf() for string input:

  • It stops reading after encountering whitespace (space, newline, etc). So it cannot read strings containing spaces.
  • If the input string is longer than the size of the target character array, there is a chance of a buffer overflow.
  • It returns the number of successful assignments made, which can be used for basic error handling.

Overall, scanf() provides a convenient way to read string data from the user in C. But we need to be mindful of its limitations.

The gets() Function in C for Reading Strings.

The C standard library function gets() is another commonly used function to read string input in C. It reads a line from stdin into the buffer pointed to by its character array argument.

Let’s look at an example:

#include <stdio.h>

int main() {
  
  char fullName[50];

  printf("Enter your full name: ");
  gets(fullName);

  printf("Your name is: %s", fullName);

  return 0;
}

Output:
Enter your full name: Rohan Verma
Your name is: Rohan Verma

In this program, gets() will read the user’s line input into the fullName character array.

Some key points about gets():

  • It reads the entire line, including whitespace characters like spaces.
  • It can lead to buffer overflow issues if the input size exceeds the buffer size.
  • Does not have a way to limit input length or perform error handling.

So, while gets() provides a simple way to read a string with spaces, we need to be careful with buffer overflows.

Key Differences Between scanf() and gets() in C

Major Difference:

  • In contrast to gets(), which stops reading when it reaches whitespace and instead treats it as a string, scanf() reads input until it reaches whitespace, a newline, or End Of File (EOF).
  • When compared to gets(), scanf can read many values of various data kinds, while the latter can only read character string data.
Featurescanf()gets()
DefinitionReads input from keyboard based on provided format specifiers. Stops at whitespace, newline, or end of file.Accepts keyboard input until reaching newline or end of file. Considers whitespace as part of input.
WhitespaceDoes not count whitespace as input. Halts at whitespace.Counts whitespace as input. Continues reading after whitespace.
SyntaxTakes a format string and addresses variables as arguments. e.g. scanf(“%d”, &number);Takes only the variable name to store input. e.g. gets(name);
Data TypesCan read multiple data types based on format specifiers.Only accepts string input.
Buffer SizeRequires specifying buffer size for string inputs.Automatically allocates buffer size.
Return ValueReturns a number of successful input conversions.Does not return any value.

Best Practices for Reading Strings in C

Based on the above comparison, here are some best practices one must follow for reading strings safely in C:

  • Always validate string lengths before reading to prevent buffer overflows.
  • Use format specifiers with scanf(), but also check return values.
  • Avoid gets() given the lack of bounds checking – use fgets() instead.
  • For user input, trim newlines and whitespace as needed after reading strings.
  • Use fixed-size character arrays or dynamically allocated memory to store strings.

Here is an example of a more robust string input routine using fgets():

#include <stdio.h>

int main() {

  char name[50];

  printf("Enter your name: ");

  // Use fgets() instead of gets()
  if (fgets(name, 50, stdin) != NULL) {
    
    // Trim newline if present
    name[strlen(name)-1] = '\0'; 
    
    printf("Your name is: %s", name);
  }
  else {
    printf("Error reading input");
  }

  return 0;
}

This helps avoid buffer issues while also adding validation and newline handling.

Conclusion

Reading string data from the user is a common requirement in C programming. Both scanf() and gets() allow us to read strings but have different behavior, especially in terms of whitespace handling and error checking.

It is important to pick the right one based on whether we need to allow whitespace and need to implement our own input validation. With some care, we can use these functions to robustly read string input in C without running into issues like buffer overflows.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *