About the C language buffer.

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

#include <stdio.h>
#include <string.h>

int main()
{
    char ss[100];
    char tt[100];

    printf("ss input : ");
    scanf("%s", ss);

    printf("tt input : ");
    gets(tt);

    printf("ss output : ");
    printf("%s", ss);

    printf("tt output : ");
    puts(tt);

    return 0;
}

In the code above, enter a value in ss through the scanf() function Next, I'm trying to enter a value in tt through the get() function I can't enter the value and just move on. I think it's because there's already a value in the buffer Am I right to understand? But the irony is that if you look at the code below, you can enter an array through the get() function Then, you can enter an array in the scanf() function, unlike the code above. Looking at it like this, I don't understand why the above code doesn't work as I intended. I'm not sure if there is a buffer on the computer for each variable to be input or if it's shared as one buffer.

I'm not sure if I'm doing a good job writing questions Please help me

#include <stdio.h>
#include <string.h>

int main()
{
    char ss[100];
    char tt[100];

    printf("tt input : ");
    gets(tt);

    printf("ss input : ");
    scanf("%s", ss);

    printf("tt output : ");
    puts(tt);

    printf("ss output : ");
    printf("%s", ss);

    return 0;
}

c

2022-09-20 08:58

1 Answers

When you read a string with the scanf function, the array stores characters from the first non-blank character (space, tab, '\n', etc.) to the time when you meet the blank character again in the buffer of the standard input. If you encounter a blank character, leave it in the buffer and exit saving. Therefore, if you enter abc and enter, abc is stored as an array and the ASCII code '\n' for the enter value remains in the buffer of the standard input.

The gets function, on the other hand, stores everything from the very beginning of the standard input buffer to the first meeting '\n' in the array. At this time, '\n' disappears from the buffer and is not stored in the array.

Therefore, if you use the gets function immediately after you use the scanf function as a question, the gets function reads the '\n' left by the scanf function, and the subsequent values are not read, so there is no value stored in the array as gets.

For your information, the gets function is deprecated in the standard environment and can no longer be used. You can use the fgets function instead, which requires attention in that it stores '\n' even in the array.


2022-09-20 08:58

If you have any answers or tips


© 2022 pinfo. All rights reserved.