简体   繁体   中英

How can I stop receiving input with a input in C

I need to constantly get commands from the user and for that I wrote this:

scanf("%s %d %s %d", str1, &num1, str2, &num2);

The user should enter something like:

move 8 over 3

When the user type exit and enter, just this line, I must stop reading and print the result. The problem is, I have no idea how to do it. The context of the code:

do{
    scanf("%s %d %s %d", str1, &num1, str2, &num2); 

    do_stuff(vp, str1, str2, num1, num2, size);
}while (strncmp(str1, exit, 4)); // I used this but I must write (exit 1 exit 1) at least.

In strncmp() , exit is a string, with "exit", so comparing these four first characters I can stop the loop, but I necessarily need to type all four expected inputs.

As kaylum pointed out, it's better to use fgets in this case. That will give you the entire line at once, but more importantly, it allows you to set a maximum size. If scanf reads more input than can fit in the buffers, it will overwrite the buffers and that is dangerous.

char line[MAX_LINE]; // MAX_LINE should be a maximum input you define
while(fgets(line, sizeof line, stdin)) {
    char str1[MAX_LINE];
    char str2[MAX_LINE];

    if(strcmp(line, exit) == 0)
        break;

    // sscanf works like scanf, except it reads from a string
    // it is safer because you now have a string of a maximum size
    int r = sscanf(line, "%s %d %s %d", str1, &num1, str2, &num2);
    if(r == 4)
        do_stuff(vp, str1, str2, num1, num2);
    else
        puts("Wrong input format. Try again");
}

You can try this:

while ((scanf("%s", &str1) == 1) && strcmp(str1, "exit")) {
     scanf("%d %s %d", &num1, str2, &num2);

     do_stuff(vp, str1, str2, num1, num2, size);
}

I made this example code and it worked for me, basically this let us enter values for the four variables needed and stop the loop when strcmp(str1, "exit") == 0 , notice that 4 values are being entered in two scanf(), I do not know what implications it may have for the buffer.

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

void do_stuff(char *str1, char *str2, int num1, int num2) {
    printf("     entered: %s %d %s %d\n", str1, num1, str2, num2);
}

int main() {

    char str1[100], str2[100];
    int num1 = 0, num2 = 0;

    while ((scanf("%99s", &str1) == 1) && strcmp(str1, "exit")) {
        scanf("%d %99s %d", &num1, str2, &num2);

        do_stuff(str1, str2, num1, num2);
    }
    printf("     loop finish!");

    return 0;
}

Command line:

move 8 over 3
     entered: move 8 over 3
move 4 over 2
     entered: move 4 over 2
exit
     loop finish!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM