morgancodes
morgancodes

Reputation: 25285

Dead-simple example of an interactive command-line application in c or objective-c?

I'd like to write a simple interactive command line program in C or Objective-C. Something that prompts the user for input and then acts on that input, then prompts the user for more input. I've googled "interactive command line application" and several variations on that theme but am not coming up with any simple examples of what I'm looking for.

This seems like an absolutely elementary, fundamental programming example, like a step after "hello world". Can anyone point me to an example of such a program, or tell me what I should be searching for?

Upvotes: 3

Views: 6284

Answers (3)

Seerex
Seerex

Reputation: 1

  1. Create a new file in Xcode
  2. select the command line tool, under the mac at the right side tab.
  3. As for type, select foundation for objective-c, and c for c.

you now get a stubbed-out project, with some stuff already made. You type your code where is has the first "NSLog" statement. Simply remove that statement, and type in your own.

Notice: NSLog is an objective-C form of getting stuff printed in the console, and for each NSLog call it will appear on a new line.

Printf is the c way of doing the same thing, but in order to print to a new line you must use \n - as a convention, it is normal that printf calls always ends with a \n

Try it out for yourself, take this into a command line project (at the place where it already has an NSLog statement) - replace it with 2 NSLog calls and 2 printf functions.

Upvotes: 0

Anne
Anne

Reputation: 27073

Xcode 4 - Foundation Command Line Tool

  1. File > New > New Project
  2. Mac OS X > Application > Command Line Tool
  3. Choose Name
  4. Type > Foundation
  5. Next
  6. Create
  7. Open the main.m file
  8. Paste the code below
  9. Hit run

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    @autoreleasepool {

        int inputOne;
        NSLog (@"Enter number: ");
        scanf("%i", &inputOne);

        int inputTwo;
        NSLog (@"Enter another number: ");
        scanf("%i", &inputTwo);

        NSLog (@"%i + %i = %d", inputOne, inputTwo, inputOne + inputTwo);

    }
    return 0;
}

Note: In case the command line interface does not appear, hit the second button:

Screenshot

Now you can interact with the command line tool.

Upvotes: 7

pmg
pmg

Reputation: 108988

There are many ways you can get input into a program. One of the most basic is scanf.

#include <stdio.h>
int main(void) {
    int age;
    printf("Enter your age: ");
    fflush(stdout);
    if (scanf("%d", &age) == 1) {
        if (age < 18) printf("baby\n");
        else if (age < 65) printf("adult\n");
        else printf("old\n");
    } else {
        printf("Invalid input\n");
    }
    return 0;
}

Upvotes: 2

Related Questions