C language “refuse scanf, start from me”

Time:2022-6-10

Hello, I’m here. I’m Meng Jie

Some time ago, I wanted to implement a command-line tool (similar to cmd.exe), so I picked up the C language that has not been used for thousands of years and wrote input and output.

That’s the problem. The scanf function I used doesn’t accept null characters. As long as I don’t enter anything, pressing enter still won’t end,I can bear it???

As a jerk who has been working on computers for eight years, I certainly have my own way. It may not be good, but it can solve the current problem.

I think many friends already know what to do, but there are still some Mengxin who don’t know how to solve this problem. Let me talk about it today.

Problem solving ideas

My idea is to use a loop to continuously receive characters through the getchar function, and then store the characters in the string.

Just do what you say. Last night I spent some time implementing this function. Here is my code.

#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
    //The outer loop allows the program to return to the original place and re-enter the command after each command execution
    while (1)
    {
        //Command string
        char command[128];
        //Accumulator, indicating that the currently entered character corresponds to the subscript in the command string
        int scannerIndex = 0;
        //Clear command string (avoid buffer problems)
        memset(command, 0, sizeof(command));
        //Print command
        printf("Command > ");
        //Inner layer loop, receiving characters
        while (1)
        {
            //Receive character temporary storage location
            char buff = getchar();
            //Judge whether the character is carriage return. If yes, let the accumulator return to zero and exit the cycle
            if (buff == '\n')
            {
                scannerIndex = 0;
                break;
            }
            //If not, save the entered characters to the command string
            command[scannerIndex] = buff;
            //The value of the accumulator increases
            scannerIndex++;
        }
        //Judge whether the command is empty. If it is empty, stop the loop and execute it again
        if (strlen(command) == 0)
            continue;
        //Now you can start to write the contents of the command operation
        //Code Here
        

    }
    return 0;
}

The results are as follows
C language
You can see that when I leave blank, it will be directly re executed, which solves the problem of scanf.

Am I the kind of person who is only half as polite? Of course not, so let’s continue to implement the command program.

Next, I want to add a function to split command names and parameters. Like CMD and many other command-line tools, the commands and parameters of the command line are separated by spaces. That’s easy. Let me give you a chestnut here. My command has only one parameter. For example, echo command, I only need to output the first parameter.

So I’ll write the code for the split command.

//Since strtok, a function that splits strings, destroys the original string, I declare a buff string again
char buff[128];
//Clear buff string
memset(buff, 0, sizeof(buff));
//Copy the contents of the command string to the buff string
strcpy(buff, command);
//Declare the key and value strings. Key is the command, and value is the parameter.
char key[64], value[64];
//Clear key string
memset(key, 0, sizeof(key));
//Empty value string
memset(value, 0, sizeof(value));
//Intercept the contents before '' (space) to key
strcpy(key, strtok(buff, " "));
//Intercept the contents after '' (space) to value, and leave the first parameter of strtok function blank to continue the previous interception
strcpy(value, strtok(NULL, " "));

So far, in fact, we have saved the command and parameter to key and value respectively

Then I can start to judge what the command is and what the program should do.

In fact, it’s very simple. From here on, it’s like if else

//If the command is echo, output parameters
if (!strcmp(key, "echo"))
{
    printf("%s\n", value);
//If the command is list, output "the command is under development"
} else if (!strcmp(key, "list"))
{
    printf("This command is developing!\n");
//If none, output "wrong command"
} else
{
    printf("Error command!\n");
}

After the above is written, we can compile and execute the source code. The final result should be as follows

As shown in the figure above, when I input echo Hello, the program outputs hello

Enter list\ This command is developing!

Error command will be output if other commands are accessed!

Final source code display

#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
    while (1)
    {
        char command[128];
        int scannerIndex = 0;
        memset(command, 0, sizeof(command));
        printf("Command > ");
        while (1)
        {
            char buff = getchar();
            if (buff == '\n')
            {
                scannerIndex = 0;
                break;
            }
            command[scannerIndex] = buff;
            scannerIndex++;
        }
        if (strlen(command) == 0)
            continue;
            
        //Code Here
        /***
         * splice the command
         * key: command
         * value: argument
         **/
        char buff[128];
        memset(buff, 0, sizeof(buff));
        strcpy(buff, command);
        char key[64], value[64];
        memset(key, 0, sizeof(key));
        memset(value, 0, sizeof(value));
        strcpy(key, strtok(buff, " "));
        strcpy(value, strtok(NULL, " "));
        
        /***
         * run command
         **/
        if (!strcmp(key, "echo"))
        {
            printf("%s\n", value);
        } else if (!strcmp(key, "list"))
        {
            printf("This command is developing!\n");
        } else
        {
            printf("Error command!\n");
        }

    }
    return 0;
}

Thank you for reading my article. If you have other views or ideas, you can comment at the bottom of my article

Welcome to my wechat group
C language

Recommended Today

jsp message board source code 1: for jsp beginners.

jsp message board source code 1: for jsp beginners.Author: precom (preserved egg)Oracle data table creation. create table guestbook ( lw_title varchar2(100) not null, — message subjectlw_author varchar2(20) not null, –Online name pkauthor_http varchar2(40) , — homepage addressauthor_email varchar2(40) not null,–email pkexpression varchar2(2) not null,–expressionlw_time varchar2(14) not null,–post response timeanswer_num number(3) not null,–response numberclick_num number(4) not […]