PDA

View Full Version : How do I get an integer user input from command line?




ataylor2009
Mar 18, 2009, 06:37 PM
I've looked in the NSString class reference, but didn't find anything that looked correct. scanf("%i", &varName) isn't working. What am I doing wrong?

int varName;
NSLog (@"Enter a number: ");
scanf("%i", &varName);
NSLog (@"You entered %i.", varName);

When I run this, I get the prompt "Enter a number:" followed by a blinking cursor. However, when I enter a number (or a letter or a space or just press return) nothing happens. Cursor moves to a new line and waits for input. I have to stop the process from the Xcode console window.

Thanks in advance.



Saladinos
Mar 18, 2009, 06:41 PM
http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/fgets.3.html

mdeh
Mar 18, 2009, 06:56 PM
I've looked in the NSString class reference, but didn't find anything that looked correct. scanf("%i", &varName) isn't working. What am I doing wrong?

int varName;
NSLog (@"Enter a number: ");
scanf("%i", &varName);
NSLog (@"You entered %i.", varName);

When I run this, I get the prompt "Enter a number:" followed by a blinking cursor. However, when I enter a number (or a letter or a space or just press return) nothing happens. Cursor moves to a new line and waits for input. I have to stop the process from the Xcode console window.

Thanks in advance.


I just ran it and it works just fine for an integer, which is what you are asking for in scanf. ( the term "varName" for int is a little confusing). If you enter anything other than an integer, you are betraying what you asked for.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int integerVal;
NSLog (@"Enter a number: ");
scanf("%i", &integerVal);
NSLog (@"You entered %i.", integerVal);
[pool drain];
return 0;
}

ataylor2009
Mar 18, 2009, 07:28 PM
Figured it out (well, I figured ONE thing out, anyway)...hitting the "Enter" key on the numeric keypad doesn't work; hitting "Return" on the main keyboard does.

I think that confuses me more than my original problem...anybody have an explanation (and a fix? I certainly want my users to be able to press whichever enter key floats their boat) for that one?

Thanks for your help, BTW.

autorelease
Mar 18, 2009, 08:03 PM
Use fgets() to read the input as a string, then convert the string to an integer with strtol().

jw2002
Mar 20, 2009, 12:43 AM
Use fgets() to read the input as a string, then convert the string to an integer with strtol().

Agree. I have never had good luck with scanf(). It doesn't have the robust error detection capabilities that strtol() has, so if the user enters "blort" or "6.4", then you are at the mercy of scanf() and whatever junk it decides to dump into your integer pointer.