[英]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: 可能是:
as a second example cp
作为第二示例
cp
this indicates that the premise of only 1 or 2 strings is not valid 这表示仅1个或2个字符串的前提无效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.