Site icon DataFlair

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

scanf() vs gets() function in c

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:

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.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

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

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:

Feature scanf() gets()
Definition Reads 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.
Whitespace Does not count whitespace as input. Halts at whitespace. Counts whitespace as input. Continues reading after whitespace.
Syntax Takes 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 Types Can read multiple data types based on format specifiers. Only accepts string input.
Buffer Size Requires specifying buffer size for string inputs. Automatically allocates buffer size.
Return Value Returns 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:

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.

Exit mobile version