top

Search

C Tutorial

.

UpGrad

C Tutorial

String Input Output Functions in C

In the world of programming, strings serve as fundamental entities for the manipulation of textual data. They provide the means to handle and manipulate various forms of text, ranging from basic words to intricate documents, empowering developers to construct dynamic and interactive applications. To work with strings effectively, programming languages provide input and output functions specifically designed for handling string data. These functions allow developers to interact with users, display information, and process string-related operations. 

What is the Input and Output of a String in C?

Input functions are primarily used to obtain string data from external sources, such as user input or input streams. They enable the program to gather information and store it in variables for further processing.   Output functions, on the other hand, are responsible for displaying or writing string data to various destinations, such as the console, files, or output streams.  The commonly used standard IF statements in C are scanf() and printf().

How to Take Input of a String in C Without Spaces?

By following these steps, you can effectively obtain a string input output functions in C with examples including any whitespace characters.

1.Include the necessary header file:

#include <stdio.h> 

This ensures that the required functions and definitions are available for input/output operations.

2. Declare a character array to store the string:

char arr [200]; 

Here, we define an array called arr with a size of 200 characters. 

3. Display a prompt to the user:

printf("Enter a string without spaces: "); 

This line informs the user about the expected input.

4. Use the scanf function to read the input:

scanf("%99[^ \t\n]", str); 

In this line, scanf is employed to scan the input from the user. The format specifier %99[^ \t\n] specifies that it should read up to 99 characters (%99s) excluding whitespace characters ([^ \t\n]). This ensures that any space, tab, or newline characters are skipped during input.

5. Process the input as desired:

Example: Print the input string printf("Input string: %s\n", str); 

Here, you can perform any desired operations on the obtained string. In this example, we simply print the input string using printf.

6. End the program:

return 0; 

This statement terminates the program and returns the exit status.

Remember to adjust the size of the character array and perform appropriate error handling based on your specific needs.

Syntax for Using Scanf() Function in C

The syntax for using the scanf() function in C is as follows:

scanf(format, variable1, variable2, ...); 

Here's a breakdown of the syntax elements:

  • scanf: It is the name of the function used for input operations in C.

  • format: It is a string that specifies the format of the input to be read. 

  • variable1, variable2, ...: These are the variables where the input values will be stored. 

Working of Scanf() in C

The scanf() function in C facilitates input reading from the standard input stream, typically the keyboard, based on a specified format. It offers flexibility for reading various data types like integers, characters, strings, and more.

Here is a step-by-step breakdown of scanf() functioning:

1. Format string: As the initial argument of scanf(), the format string specifies the expected data types and their order. It employs format specifiers, starting with the % symbol, followed by a letter representing the desired data type.

2. Input retrieval: scanf() scans the input from the standard input stream, adhering to the provided format string. It begins reading characters and sequentially matches them with the format specifiers.

3. Format specifier matching: When encountering a format specifier, scanf() attempts to read the input data from the standard input stream and convert it to the specified type. Prior to reading the actual input, it disregards leading whitespace characters, such as spaces, tabs, and newlines.

4. Value assignment: By utilizing the memory addresses of the variables passed as arguments after the format string (obtained using the & operator), scanf() directly modifies their values, assigning the corresponding input values.

5. Return value: Upon completion, scanf() returns the count of successfully matched and assigned input items. This return value allows verification of whether the input was read correctly.

6. Error handling: It is essential to handle potential errors that may arise during scanf() usage. For instance, if the input doesn't match the format specifier or the input buffer overflows, scanf() may fail. Therefore, proper error handling is necessary to handle such scenarios effectively."

By following these steps and considering error handling, you can make effective use of the scanf() function in C for input operations.

Advantages of using scanf(): 

Versatility: scanf() allows you to read input of various data types, such as integers, characters, strings, and more, by using appropriate format specifiers. It provides flexibility in handling different types of user input. 

Direct assignment: scanf() assigns the input values directly to variables using their memory addresses. This simplifies the process of capturing and using user input within the program. 

Disadvantages of using scanf(): 

Input errors: scanf() can be prone to input errors and unexpected behavior. If the user enters incorrect data or the input format doesn't match the format specifier, it can result in incorrect or unpredictable program behavior. Error handling and input validation are crucial to mitigate these issues. 

Buffer overflow: When reading input using scanf(), it's important to provide buffer sizes to avoid buffer overflow. If the input exceeds the capacity of the variables or arrays, it can lead to memory corruption and security vulnerabilities. 

Limited error reporting: scanf() returns the number of successfully matched and assigned input items, but it doesn't provide detailed information about the nature of errors. It can be challenging to identify and handle specific input errors using scanf() alone.

How to Take Input of a String With Spaces in C?

There are various methods to input a string with space and accept it in C:

Methods to Accept String With Space in C

There are 4 ways to accepts a string with space in C

Let's start with a character array (string) called str[]. As a result, we've declared a variable as char str[20].

Method 1 : Using gets

Syntax : char *gets(char *str)

#include <stdio.h>
int main()
{
   char str[20];
   gets(str);
   printf("%s", str);
   return 0;
}  

Method 2 : Using fgets

Syntax : char *fgets(char *str, int size, FILE *stream)

 Example : fgets(str, 20, stdin); as here, 20 is MAX_LIMIT according to declaration.

#include <stdio.h>
#define MAX_LIMIT 20
int main()
{
   char str[MAX_LIMIT];
   fgets(str, MAX_LIMIT, stdin);
   printf("%s", str);
   return 0;
}

Method 3 : Using %[^\n]%*c inside scanf

Example : scanf(“%[^\n]%*c”, str);

#include <stdio.h>
int main()
{
   char str[20];
   scanf("%[^\n]%*c", str);
   printf("%s", str);
   return 0;
}

Explanation : The scanset character is [] in this case. ^\n informs the programme to accept input until a newline is encountered. Then, using this%*c, it reads newline characters, and the usage of * here denotes that these newline characters are ignored. 

Method 4 :  Using %[^\n]s inside scanf.

Example :  scanf(“%[^\n]s”, str); 

#include <stdio.h>
int main() {
    char str[100];
      scanf("%[^\n]s",str);
      printf("%s",str);
    return 0;
}

Explanation : The scanset character is [] in this instance. ^\n instructs the programme to accept input until no newlines are found. Here, we utilized the XOR operator, which returns true until both letters are distinct. When a character is equal to New-Line ('n'), the XOR operator returns false, making it impossible to read the string. Therefore, we substitute "%[n]s" for "%s." Consequently, we may use scanf("%[n]s",str); to obtain a line of input with a space.

Comparison between gets() and fgets()

The user can define the maximum number of characters to read with the fgets() function, and we can also change the input stream to any file using fgets(), which is the key distinction between fgets() and gets(). Use of fgets() is secure since it checks the array bound, in contrast to gets(), which may be risky because it does not.

Using scanset %[ ] in scanf()

The scanset format specifier%[] provided by the scanf() function in C enables you to read input that contains spaces and other permitted characters. To match a set of characters supplied between brackets, use the scanset%[] function.

Ways by which we can use scanset to take input of a string in C with spaces

1. {%[^\n]%*c} inside scanf 

Let's explore one way to use scanset to take input of a string with spaces in C using the format specifier {%[^\n]%*c} inside scanf().

Here's an example:

#include <stdio.h>
int main() 
{
     char str[100];
     printf("Enter a string with spaces: ");
     scanf("{%[^\n]%*c}", str);
     printf("Input string: %s\n", str);
     return 0;
}

In this example, we use the {%[^\n]%*c} format specifier inside scanf() to read a string with spaces. Let's break down the format specifier:

{ and }: The braces are literal characters that should match the input exactly. They help differentiate this format specifier from regular scanset format specifiers.

%[^\n]: This scanset format specifier matches a sequence of characters until a newline character ('\n') is encountered. It allows scanf() to read the input string with spaces.

%*c: The asterisk (*) indicates that the character read by this scanset format specifier should be discarded without assigning it to a variable. The %*c is used to read and discard the newline character after the scanset, preventing it from interfering with future input operations.

By using {%[^\n]%*c}, scanf() will read the input string until a newline character is encountered, effectively capturing the string with spaces. The string is then stored in the str array, and you can perform any necessary operations on it.

It's worth noting that the use of {%[^\n]%*c} is not a standard scanset format specifier, but rather a specific format we can define to achieve the desired input behavior.

2. %[^\n]s inside scanf

#include <stdio.h>
 int main() 
{ 
char str[100]; 
printf("Enter a string with spaces: "); scanf("%[^\n]", str); 
printf("Input string: %s\n", str); return 0;
 }

 In this example, %[^\n] is the correct scanset format specifier used in scanf(). It matches a sequence of characters until a newline character ('\n') is encountered. This allows scanf() to read the input string with spaces. After reading the input, the string is stored in the str array, and you can perform any necessary operations on it. 

How to Output a String With Spaces in C? 

1. using printf() with \n 

You can use the printf() function to output a string with spaces and include a newline character (\n) at the end to start a new line. Here's an example: 

#include <stdio.h> 
int main() 
{
 char str[] = "Hello, world!";
 printf("%s\n", str); return 0; }

In this example, we use printf() to output the string Hello, world! followed by a newline character (\n). The %s format specifier is used to print the string. 

The output will be: 

Hello, world!

The newline character \n ensures that the next output appears on a new line.

2. using puts() 

The puts() function is specifically designed to output a string and automatically adds a newline character (\n) at the end. Here's an example: 

#include <stdio.h> 
int main() 
{ 
char str[] = "Hello, world!"; 
puts(str); return 0; 
}

In this example, we use puts() to output the string Hello, world!. It automatically appends a newline character at the end of the string. 

The output will be: 

Hello, world! 

Using puts() simplifies the process of printing a string with spaces and ensures that each output appears on a new line.

Conclusion

Strings play a crucial role in coding as they form the foundation for effective text manipulation. Their ability to store sequences of characters makes them versatile and applicable in various scenarios. By comprehending the unique properties of strings and mastering the input and output functions tailored for them, developers gain the ability to create dynamic and engaging applications across a wide range of domains. This understanding empowers programmers to harness the full potential of strings and leverage their capabilities for efficient text processing and manipulation.

FAQs

1. What are C String Input/Output Functions?

String Output Functions in C are a set of functions in the C programming language that facilitate reading input from and writing output to strings.

2. What are some commonly used C String Input Functions?

Some commonly used String Input Functions in C include scanf(), gets(), and fgets(). These functions allow users to input strings from various sources like the console or files.

Leave a Reply

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