Reputation: 25285
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
Reputation: 1
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
Reputation: 27073
Xcode 4 - Foundation Command Line Tool
main.m
file#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:
Now you can interact with the command line tool.
Upvotes: 7
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