简体   繁体   中英

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. 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). 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 ...

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

I suggest to use a switch-like solution. switch doesn't support char * , so else-if is needed.

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
}

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