简体   繁体   English

如何在C语言中读取各种类型的用户输入?

[英]How to read user input of various types in C?

This might be a dumb question, but I'm new to C and I realized that if you want to use scanf , you have to give it a type you're scanning. 这可能是一个愚蠢的问题,但是我对C还是scanf ,所以我意识到,如果要使用scanf ,则必须给它一个要扫描的类型。 But what if you don't know what the user will type, how can you give it a definite type? 但是,如果您不知道用户将键入什么,该如何给它定型呢?

For example, I want the user to able to give various commands such as 例如,我希望用户能够给出各种命令,例如

read file.txt
write file2.txt
delete 2 
delete 4
quit

I started off by doing 我开始做

printf("\nPlease enter a command (print, delete, write, quit): ");
scanf("%s", &str); //but I realized here how can I differentiate it? 
//i won't know what the user will type beforehand so I can't give a definite type.

The result of the scanf() for each of the listed inputs will be ONLY the first word (up to but not including the space). 每个列出的输入的scanf()结果将仅是第一个单词(最多但不包括空格)。 Suggest using fgets() to get the whole command line input into a local buffer, then parsing the data fields from the local buffer, perhaps using strtok() or strchr() or ... 建议使用fgets()将整个命令行输入到本地缓冲区中,然后从本地缓冲区中解析数据字段,也许使用strtok()strchr()或...

You can instead try something like this? 您可以尝试这样的方法吗?

int option;
printf("\nPlease enter a command (1 for print, 2 for delete, 3 for write, 4 for quit): ");

And then read the user input number 然后读取用户输入的号码

scanf("%d", &option);

You can later use a switch statement on 'option' to process differently 您以后可以在'option'上使用switch语句进行不同的处理

I suggest to use a switch-like solution. 我建议使用类似开关的解决方案。 switch doesn't support char * , so else-if is needed. switch不支持char * ,所以需要else-if。

int x;
char buff[MAX_LEN], buff1[MAX_LEN];

scanf("%s", buff);
if (!strcmp(buff, "read")) {
    scanf("%s", buff1);
    //...
} else if (!strcmp(buff, "delete")) {
    scanf("%d", &x);
    //...
} else if (!strcmp(buff, "quit")) {
    //...
    exit(0);
} else {
    //Error handle
}

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

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