这可能是个愚蠢的问题,但我是 C 的新手,我意识到如果你想使用 scanf
,你必须给它一个你正在扫描的类型。但是,如果您不知道用户会输入什么,您怎么能给它一个明确的类型呢?
例如,我希望用户能够给出各种命令,例如
read file.txt
write file2.txt
delete 2
delete 4
quit
我从做开始
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.
最佳答案
对于每个列出的输入,scanf()
的结果将只是第一个单词(直到但不包括空格)。建议使用 fgets()
将整个命令行输入到本地缓冲区,然后从本地缓冲区解析数据字段,可能使用 strtok()
或 strchr()
或 ...
关于c - 如何在C中读取各种类型的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29503646/