MMGames Introduction to C C Language Development Environment C language now Useful Apps Contact Us
MMGames

Automatic version identification

SpineViewer

It's easy to tell by looking at it.

Response Time Checker

I can leave my computer on and do it.

Mouse cleaning time

I can leave my computer on and do it.

Mouse cleaning time

C language learned by suffering
C language learned by suffering

Enter as a single line of text

Keyboard input with gets function
Previously, when using the scanf function to input data from the keyboard, the
We explained that if there is a typing error, the program cannot know about it.
As a countermeasure, we explain how to input the data as a string and read it later as a numerical value.

The C language provides the GETS function, which inputs a single line of string from the keyboard.
Note that you must #include <stdio.h> to use the gets function.
The usage of the GETS function is as follows

GETS function
 gets(character array);

When the GETS function is executed, it enters a state waiting for input, similar to the SCANF function.
The string entered by the user from the keyboard is stored in the specified character array.

And, incidentally, the puts function, which displays a single line of text on the screen, is also explained.
Note that you must #include <stdio.h> to use the puts function.
The usage of the puts function is as follows

puts function
 puts(character array);

The specified string is displayed on the screen. Also, a new line is always inserted at the end of the string.
Although less functional than the printf function, the puts function is easier if you just want to display a string.

The following program is an example of displaying a string as the user enters it.

Source Code
 #include <stdio.h>

int main(void)
{
    char str[32];

    gets(str);
    puts(str);

    return 0;
}

The result of executing this program is as follows

Execution result 1st
DRAGON QUEST 3 Input string
DRAGON QUEST 3

The input string is displayed as it is.
Unlike when using %s in the scanf function, it does not matter if spaces are included.
Buffer overrun countermeasures
Apparently, the author's twisted nature remains unfixed.
Because I am going to issue a ban on the use of the GETS function that I just explained.

Earlier, when we discussed what happens when you pass an array to a function
I explained that it is the top address of the array that is passed to the function and that the number of elements is ignored.

Earlier, we only passed a character array to the gets function.
This means that the gets function does not know the number of elements in the character array.
This means that input exceeding the number of elements will be accepted, leading to a bug.

The number of elements in the previous program was 32, so inputting more than 31 characters would cause a bug.
The following execution results are examples of actual input and viewing.

Execution Result
01234567890123456789012345678901234567890123456789 Input string


When I tried to run the program, an error screen appeared and the program was forced to terminate.

As long as there is such a problem, the gets function cannot be used.
Instead, the fgets function can be used.
Note that you must #include <stdio.h> to use the fgets function.
The usage of the fgets function is as follows

fgets function
 fgets(character array, number of array elements, file pointer);

As you can see from the fact that the file pointer is specified at the very end, the
This function is used to read a string from a file.

But in fact, in C, all peripherals can be treated as files.
The keyboard is assigned a file pointer named stdin.
By specifying this stdin, a function that reads from a file can be quickly transformed for the keyboard.

Peripherals are treated as files
File handling of peripherals is a feature introduced in the UNIX operating system.
Almost all current computers have similar mechanisms.

To know the number of elements in an array, it is easy and reliable to use the sizeof function.
In other words, the following is a safe alternative to the gets function

Instead of the safe gets function
 fgets(character array, sizeof(character array), stdin);


newline character
The gets function does not store '\n', but the fgets function does.
To find the end of the input, look up '\n'.

The following program is an example of a rewritten secure input method.

Source code
 #include <stdio.h>

int main(void)
{
    char str[32];

    fgets(str, sizeof(str), stdin);
    puts(str);

    return 0;
}

The following is the result of testing the safety level by entering a long string of characters in this program.

Execution Result
0123456789012345678901234567890123456789 input string
0123456789012345678901234567890

It can be seen that input is terminated at the limit of the number of elements, preventing bugs from occurring.
Extracting numerical values and other data from strings
Now the string input is complete, but there is still a problem.
It differs from the scanf function in that it does not allow numeric input.
The string you enter must be read as a number.

The easiest way to read strings into numbers is to use the atoi function.
Since this has already been explained, we will skip the detailed explanation.
The following program is an example that displays the square of the entered number.

source code
 #include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[32];
    int val;

    fgets(str, sizeof(str), stdin);
    val = atoi(str);
    printf("%d\n", val * val);

    return 0;
}

The result of executing this program is as follows

Execution Result
5
25

If the input string contains non-numeric characters, the atoi function ignores them.
The scanf function does not result in incomprehensible numbers, as is the case with the scanf function.
Also, counting the number of characters in the original string will tell you the number of digits in the input number, so you can use
Even if too large a number is entered, it can be checked.
For real numbers, use the atof function. The usage is the same.

This is sufficient if you simply want to enter a number.
If you want to enter multiple numbers separated by a symbol, as in the scanf function
It is necessary to search for symbols on your own and convert each to a number.

Although there is also an sscanf function
There's also an sscanf function that cuts numbers out of strings.
Because it has problems similar to those of the scanf function, we will not deal with it here.


Use the strtok function to extract words from a string.
Note that you must #include <string.h> to use the strtok function.
The usage of the strtok function is as follows

strtok function
 /* retrieve the first word */
Word address value = strtok(character array, delimiter);

/* retrieve the next word */
Word address value = strtok(NULL, delimiter);

The strtok function searches for a delimiter and replaces its position with EOS.
Strings can be split before and after the delimiter.
The word can then be converted with the atoi function to obtain a numerical value.
Returns NULL if the word is not found.

The following program is an example that displays a list of input numbers.

Source code
 #include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(void)
{
    int i, j, val[10];
    char str[32], *ch;

    fgets(str, sizeof(str), stdin);

    ch = strtok(str, ",\n");

    for (i = 0; i < 10; i++) {
        if (ch == NULL) {
            break;
        } else {
            val[i] = atoi(ch);
        }
        ch = strtok(NULL, ",\n");
    }

    for (j = 0; j < i; j++)
        printf("%d\n", val[j]);

    return;
}

The result of executing this program is as follows

Execution Result
85,41,26,956,12 Input string
85
41
26
956
12

You can increase the number of digits in a number or enter a string of characters.
There are no errors.


About this Site

The C language (bitter C), which is learned by suffering, is
This is the definitive C language introductory site.
It systematically explains the basic functions of the C language and
It is as complete as or more complete than any book on the market.

Part 0: Program Overview
  1. What is the program?
Chapter 2: How to write a program
  1. Writing Rules
  2. Writing conventions
  3. Exercise 2
Chapter 3: Display on Screen
  1. String display
  2. newline character
  3. Exercise 3
Chapter 4: Numeric Display and Calculation
  1. Numeric Display
  2. Basic Calculations
  3. Type of value
  4. Exercise 4
Chapter 5: Numerical Memory and Calculation
  1. Memorize values
  2. Variable Type
  3. Type conversion
  4. Numeric justification
  5. Exercise 5
Chapter 6: Input from the keyboard
  1. Functions for input
  2. Fear of Input
  3. Exercise 6
Chapter 9: Repetition with a fixed number of times
  1. Sentences that repeat themselves
  2. Loop Operation Mechanism
  3. Exercise 9
Chapter 10: Unknown number of repetitions
  1. Loop of unknown frequency
  2. input check
  3. Exercise 10
Chapter 13: Handling Multiple Variables at Once
  1. Multiple variables are handled together.
  2. How to use arrays
  3. Exercise 13
Chapter 19: Dynamic Arrays
  1. Create arrays at will
  2. Exercise 19
Chapter 20: Multiple Source Files
  1. Minimal division
  2. The Stone of Division
  3. Exercise 20

Comment
COMMENT

Open the 💬 comment submission box