Complementary task for topic: 5

M Nemeth · 2023-08-29 15:21:04.619219'

Simple strings: I/O

Simple strings: I/O

Write a C program that uses scanf() to read a string from the user and then uses printf() to display the entered string.

Hint: Strings are character arrays, it is terminated by "End-of-String" character, but now you do not need to use this, as scanf() will take this character to the end of the string. The array size is usually not equal to the number of required characters. That is not a problem.

Solution
#include 

int main() {
    char str[100];

    printf("Enter a string: ");
    scanf("%99[^\n]", str); // Read the string with spaces max. 99 chars, till enter hit

    printf("You entered: %s\n", str);

    return 0;
}



Explanation
Explanation:

    The program uses a char array str to store the input string.

    The user is prompted to enter a string using printf().

    The string is read using scanf() with the %[^\n] format specifier, which reads characters until a newline character is encountered. This allows us to read a string with spaces.

    The entered string is displayed back to the user using printf() with %s format specifier, which is used to display strings.
< < previous    next > >