what is the correct way to handle multiple input command differently in c++?

前端 未结 5 693
深忆病人
深忆病人 2021-01-12 16:24

I have a program that take commands from user and it will process different commands differently. For example:

ADD_STUDENT ALEX 5.11 175
ADD_TEACHER MERY 5.4         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 16:47

    You could technically tokenize the entire input line, but that seems a little too far out from your level. If you did want to go into it, there is a nice page and tutorial here that will help you use strtok().

    If you do not want to go that method, you can individually parse through your list of commands. Say you have read into a string named "command".

    if (command == "ADD_STUDENT")
    {
        int weight, height, otherfield;
        cout << ">" << flush;
        cin >> weight >> height >> otherfield;
        //do something, like add them to the database
    }
    

    That seems like your best bet, although it is a lot of coding, it is probably easier for you to accomplish. You could get really into it and use format strings like this:

    scanf("%s, %s %d, %f", lastname, firstname, age, height);
    

    This way, the input would look like this:

    ADD_STUDENT Doe, John 30, 5.6
    

提交回复
热议问题