Kara
Kara

Reputation: 785

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.

Upvotes: 0

Views: 74

Answers (3)

Endle_Zhenbo
Endle_Zhenbo

Reputation: 576

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
}

Upvotes: 0

Srivatsa
Srivatsa

Reputation: 21

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

Upvotes: 1

user3629249
user3629249

Reputation: 16540

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

Upvotes: 2

Related Questions