MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

Enter as a single line of text.

Keyboard input using the gets() function
Previously, when taking input from the keyboard using the scanf function,
I explained that the program wouldn't know about input errors.
As a workaround, I will explain how to enter it as a string and then convert it to a number later.

C language provides a function called gets() that allows you to input a line of characters from the keyboard.
Note that you need to include <stdio.h> to use the `gets` function.
The following is how to use the gets() function.

gets function
gets(文字array);

The `gets` function, like `scanf`, will enter a waiting-for-input state.
The string entered by the user from the keyboard is stored within a designated character array.

"Also, while I'm at it, I'll also explain the puts function, which displays a line of text on the screen."
"Note that you need to include `` to use the `puts` function."
The usage of the puts function is as follows.

puts function
puts(文字array);

The specified string will be displayed on the screen.Also, it will always end with a newline.
While less functional than the printf function, the puts function is simpler for displaying strings only.

The following program is an example of displaying a string entered by the user.

Source code
#include <stdio.h>

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

    gets(str);
    puts(str);

    return 0;
}

The output of this program is as follows:

First execution result
DRAGON QUEST 3 入力した文字列
DRAGON QUEST 3

The input string is being displayed as is.
Unlike when using %s with the scanf function, it works fine even with spaces.
Buffer overflow protection
It seems the author's cantankerous personality hasn't improved at all.
Because I intend to issue a prohibition against the use of the gets function I just explained.

When I explained earlier how to pass an array to a function,
I explained that a function is passed the address of the beginning of the array, and the size of the array is ignored.

I was only passing character arrays to the `gets` function before.
This means the `gets` function doesn't know the size of the character array.
This means it accepts input exceeding the number of elements, which leads to a bug.

"Since the previous program had 32 elements, entering more than 31 characters would cause a bug."
The following results are examples of what you'd see when you actually enter the input.

Execution results
0123456789012345678901234567890123456789 入力した文字列


When I tried to run it, an error screen appeared and it crashed.

As long as there is such a problem, the `gets` function cannot be used.
Alternatively, you can use the fgets function.
"Note that you need to include <stdio.h> to use the fgets function."
The fgets function is used as follows:

fgets function
fgets(文字array, arrayの要素数, FilePointer);

As can also be seen from the fact that the file pointer is being specified,
This function reads a string from a file.

However, the truth is that in C, all peripheral devices can be treated as files.
A file pointer named stdin is assigned to the keyboard.
"By specifying this stdin, functions that read from files can quickly switch to reading from the keyboard."

Peripherals are treated as files.
周辺機器のFile扱いは UNIX というOSで取り入れられた機能で、
現在のコンピュータはほとんどすべてが同様の仕組みを備えています。

It's easy and reliable to know the number of elements in an array using the sizeof operator.
"That is, you can achieve a safe alternative to the `gets` function by doing the following."

Safe alternatives to gets
fgets(文字array, sizeof(文字array), stdin);


newline character
gets functionは '\n' を格納しませんが、fgets functionは格納します。
入力の終わりを調べるには '\n' を検索してください。

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

Source code
#include <stdio.h>

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

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

    return 0;
}

The results of testing the safety of this program with a long string input are as follows.

Execution results
0123456789012345678901234567890123456789 入力した文字列
0123456789012345678901234567890

It appears the input is being cut off at the point where the element count reaches its limit, preventing bugs.
Extract numbers and other values from a string.
While string input is now foolproof, issues remain.
"The difference is that it cannot accept numeric input, unlike the scanf function."
You need to convert the input string to a number.

The easiest way to convert a string to a number is to use the atoi function.
As it has already been explained, I will omit the details.
The following program is an example that displays the square of an input 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 output of this program is as follows:

Execution results
5
25

"Since the atoi function ignores any characters other than digits in the input string,"
You won't get those inexplicable numbers you sometimes see with scanf.
Also, counting the number of characters in the original string reveals the number of digits entered.
It can also check for inputs that are too large.
Furthermore, the `atof` function is used for real numbers.It's the same way to use.

Simply entering numbers is sufficient with this.
"When you want to input multiple numbers separated by a delimiter, similar to the scanf function,"
You need to find the symbols yourself and convert each one to a number.

There's also the sscanf function.
文字列からnumericsを切り出すsscanf functionもあるのですが、
scanf functionと似た問題があるので、ここでは扱いません。


To extract words from a string, you use the strtok function.
Please note that you need to include <string.h> to use the strtok function.
The usage of the strtok function is as follows.

strtok function
/* 初めの単語を取り出す */
単語のaddress値 = strtok(文字array, 区切り文字);

/* 次の単語を取り出す */
単語のaddress値 = strtok(NULL, 区切り文字);

The strtok function searches for delimiters and replaces them with null terminators (EOS).
You can split a string into sections before and after a delimiter.
After that, you can obtain a numerical value by converting the word with the atoi function.
Return NULL if the word is not found.

The following program is an example of displaying a list of entered 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 output of this program is as follows:

Execution results
85,41,26,956,12 入力した文字列
85
41
26
956
12

Whether you increase the number of digits or enter a string,
You will never encounter an error.


About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.

Part 0: Program Overview
  1. What is a program?
Chapter 3: Displaying on the Screen
  1. String Display
  2. newline character
  3. Practice Problem 3
Chapter 4: Displaying and Calculating Numbers
  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4
Chapter 6: Input from the Keyboard
  1. input function
  2. The fear of input
  3. Practice Problem 6
Chapter 9: Repeating a Fixed Number of Times
  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9
Chapter 10: Repeating Without Knowing the Number of Times
  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10
Chapter 13: Handling Multiple Variables at Once
  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13
Chapter 19: Dynamic Arrays
  1. Create arrays freely.
  2. Practice Problem 19