简体   繁体   English

C:如何将用户输入限制为2个以空格分隔的参数?

[英]C: How do you limit user input to 2 arguments separated by a space?

I am trying to build a directory tree. 我正在尝试建立目录树。

How can you limit user input to 1-2 strings separated by spaces? 如何将用户输入限制为以空格分隔的1-2个字符串?

USER INPUT EXAMPLE: 用户输入示例:

mkdir directory1 (2 strings: one command one argument) mkdir directory1(2个字符串:一个命令一个参数)

ls (1 string: one command) ls(1个字符串:一个命令)

Some ideas: 一些想法:

Tokenise user input AND 标记用户输入AND

Delimiter for white-spaces to check for new string 空格分隔符以检查新字符串

OR Pointer to traverse the char elements of the strings? 指针遍历字符串的char元素?

But how do you handle for the 3rd string eg if (string_count > 2) {error message} 但是您如何处理第三个字符串,例如if(string_count> 2){错误消息}

#include <stdio.h> /* For fgets(), fprintf() and printf() */
#include <stdlib.h> /* For EXIT_FAILURE */
#include <ctype.h> /* For isspace() */

// COMMANDS
char exit[4] = "exit";
char list[2] = "ls";
char commandDirectory[2] = "cd";
char makeDirectory[5] = "mkdir";
char removeDirectory[5] = "rmdir";
char directoryName[129] = "";

int userInput() {
    char string[130];

    printf("> \n");
    printf("Input a string: ");
    if (fgets(string, sizeof(string), stdin) == NULL) {
        fprintf(stderr, "Please enter at least one argument\n");
    }
    else
    {
        char *pointer;

        pointer = string;
        while (isspace((unsigned char) *pointer) != 0)
            pointer++;
        if (*pointer == '\0') {
            fprintf(stderr, "Please enter at least one argument\n");
        }
        printf("%s", string);
    }
    return 0;
}

int main(void) {
    userInput();
}

the easiest way to ignore unexpected input.. 忽略意外输入的最简单方法。

after reading any expected/optional input, just loop calling getchar() until a '\\n' char is read. 读取任何期望的/可选的输入后,只需循环调用getchar()直到读取'\\ getchar()

given your ls input. 输入您的ls that could be: 可能是:

  1. ls LS
  2. ls -al ls -al
  3. ls -al myfile ls -al myfile
  4. and several other possibilities 和其他几种可能性

as a second example cp 作为第二示例cp

  1. cp filename1 directoryname cp filename1目录名
  2. cp filename1 filename2 directoryname cp filename1 filename2目录名
  3. cp -a --attributes-only --backup -force filename1 filename2 cp -a-仅属性-备份-force filename1 filename2
  4. and several other possibilites 和其他几种可能性

this indicates that the premise of only 1 or 2 strings is not valid 这表示仅1个或2个字符串的前提无效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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