C Programming Examples Tutorial Index

C String Programs

In C programming, handling user input and displaying output are fundamental concepts. This tutorial focuses on a simple C program that prompts the user to input a string and then prints that string to the screen. You will explore how to use the scanf() function to read a string entered by the user and the printf() function to display the string.



Understanding scanf() and printf() Functions

The scanf() function is used to read formatted input from the keyboard, while printf() is used to print formatted output to the screen. These functions are crucial for basic input/output operations when working with strings in C.

Example Program:

Below is a straightforward example demonstrating how to prompt for and read user input and then display that input using the scanf() and printf() functions. The program includes comments to help you understand each part of the process.

// Include the Standard Input/Output library for using printf() and scanf()
#include<stdio.h>

// The main function where the execution of the program begins
int main() {
    // Declare a character array (string) to store user input
    char stringArray[100];

    // Prompt the user to enter some text
    printf("Please write something: \n");

    // Use scanf() to read the input string entered by the user.
    // Note: scanf() with %s reads input until the first whitespace is encountered.
    scanf("%s", stringArray);
    
    // Display the input string back to the user
    printf("You entered the string: %s\n", stringArray);
    
    // Return 0 to indicate successful completion of the program
    return 0;
}

Program Output:

When you run the program, it will prompt you to write something. After you input your text and press Enter, it will display your entered string. Here's an example of how the program works:

Please write something:
W3schools.in
You entered the string: W3schools.in

This program demonstrates a basic use of scanf() to capture user input and printf() to display that input back to the user. It's important to note that using scanf() with %s will only read input up to the first whitespace. Other functions like fgets() may be more appropriate for reading entire lines of text, including spaces.

Conclusion

This tutorial covered how to input and display strings in C using the scanf() and printf() functions. Understanding and utilizing these basic input/output functions is crucial for developing more complex programs in C. They form the foundation for user interaction, allowing for dynamic and responsive command-line applications.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram