Running C scripts with terminal instead of Xcode

前端 未结 3 590
时光取名叫无心
时光取名叫无心 2021-01-07 11:50

Currently I am developing a couple of C programs on my mac using Xcode. There however is 1 problem. My study requires me to use some sort of input field through the coding.

3条回答
  •  鱼传尺愫
    2021-01-07 12:01

    Sounds to me like you want to get your arguments from the command line and if they are missing, prompt the user for them

    Lets assume you want the arguments: number word number

    #include 
    #include 
    
    int number1;
    char word[128];
    int number2;
    
    int main(int argc, const char **argv)
    {
        if (argc == 4)
        {
            number1 = atoi(argv[1]);
            strcpy(word, argv[2]);
            number2 = atoi(argv[3]);
        }
        else
        {
            do
                printf("Enter number word number: ");
            while (scanf("%d %s %d", &number1, word, &number2) != 3);
        }
    
        printf("I got %d '%s' %d\n", number1, word, number2);
        return 0;
    }
    

    Which gives:

    $ ./test
    Enter number word number: 1 andy 12
    I got 1 'andy' 12
    $ ./test 2 pandy 56
    I got 2 'pandy' 56
    

    Note that the error-checking is poor in this example and can be improved alot (not using atoi() is one way to start).

提交回复
热议问题