简体   繁体   中英

Is it possible to scanf multiple times without a newline in output?

Im a beginner to c and want to make my code to ask for a command and if 's' is entered it then receives a second number:

void get_command(char *command) {
    struct pizzeria *the_pizzeria;
    printf("n - new order, s# - select order #, x - exit\n");
    get_char_input(command, "Command: ", MAX_COMMAND_LENGTH);

}

//....

void process_command(struct pizzeria *the_pizzeria, char *command) {
    if (command[0] == 'n') {
        struct order **last_next_order_field = get_last_next_order_field(the_pizzeria);
        *last_next_order_field = create_order();
    }

    if (command[0] == 's') {
        get_integer_input(&the_pizzeria->selected_order, "");
        printf("\n \n");
    }

}

//....

void get_integer_input(int *variable, char *prompt) {
    
    printf(prompt);
    scanf("%d", variable);

    getchar();

}

I want to get a result of: Command: s2

However I get receive:

Command: s 
2

I tried using getchar() and fflush(stdnin) but it didn't work. I have also attempted fgets() and didn't make any progress.

Edit:

Function get_char_input()


void get_char_input(char *variable, char *prompt, int length) {

    printf(prompt);
    fgets(variable, length, stdin);

    variable[strcspn(variable, "\r\n")] = 0;

}

Note: command is a char variable with the max length of 16.

From the following:

printf("n - new order, s# - select order #, x - exit\n");
get_char_input(command, "Command: ", MAX_COMMAND_LENGTH);

one 'presumes' that command is a multi-character buffer, and you prompt "s#" for entry of "s207" (for example).

This would do what you seem to want:

if (command[0] == 's') {
    the_pizzeria->selected_order = atoi( command + 1 );

You may want to add validation that the number returned is sensible. It may often be 0.

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