Use scanf() for first letter - objective-c

I have somewhat of a command line where the user types in 1 letter, and when the user types in more than 1 letter, the program takes the first letter typed. How do I go about doing this, as what I'm doing doesn't seem to work out for me:
char ans, *d;
Sequence *seq = [[Sequence alloc] init];
while (k < 10) {
k++;
[seq generate];
printf("%i. %s\n\n>>> ", k, [seq.full cStringUsingEncoding:NSUTF8StringEncoding]);
scanf("%c%s", &ans, &d);
NSString *input = [NSString stringWithFormat:#"%c", ans];
if (input == seq.answer) {
correct ++;
}
}
EDIT: I just want to clarify that the 'd' variable is used as a dummy, so that the Enter key doesn't get registered.

Have you looked in < curses.h> to see what the getch() function does?
Please Refer: http://pubs.opengroup.org/onlinepubs/7908799/xcurses/curses.h.html
Its for Mac...

Related

Substring with range out of bounds?

Okay, so this is a bit confusing (well to me). I have a string that has a single number I want out of it. I have surrounded this number with '/' so that I will be able to get that number out of it later.
Here is how I am getting the number out of it:
if ([MYSTRING hasSuffix:#"mp"]) {
int start = 0;
int end = 0;
char looking = '/';
for(int i=0; i < MYSTRING.length; i++){
if (looking == [MYSTRING characterAtIndex:i]) {
if (start == 0) {
start = i;
}
else{
end = i + 1;
}
}
}
NSLog(#"%#", MYSTRING); //When i NSLOG here i get '2012-06-21 03:58:00 +0000/1/mp', 1 is the number i want out of the string, but this number could also change to 55 or whatever the user has
NSLog(#"start: %i, end: %i", start, end); //When i NSLOG here i get 'start: 25, end: 28'
NSString *number = [MYSTRING substringWithRange:NSMakeRange(start, end)];
number = [number stringByReplacingOccurrencesOfString:#"/" withString:#""];
if ([number intValue] > numberInt) {
numberInt = [number intValue];
}
It keeps crashing and the console says:
* Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range or index out of bounds'
* First throw call stack:
(0x1875d72 0x106ce51 0x1875b4b 0x184ea64 0x3a6c 0x1080713 0x1bf59 0x1bef1 0xd532e 0xd588c 0xd49f5 0x49a2f 0x49c42 0x290fe 0x1b3fd 0x17d2f39 0x17d2c10 0x17ebda5 0x17ebb12 0x181cb46 0x181bed4 0x181bdab 0x17d1923 0x17d17a8 0x18e71 0x200d 0x1f35)
libc++abi.dylib: terminate called throwing an exception
From my counting the range is within the bounds, I dont get why I am getting this error?
Any help would be appreciated.
Thanks
Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);
I think you have confusion in syntax of NSMakeRange. It is something like this
NSMakeRange(<#NSUInteger loc#>, <#NSUInteger len#>)
<#NSUInteger loc#>: It is the location from where you want to start picking or substring.
<#NSUInteger len#>: This is the length of your output or substring.
Example:
Mytest12test
Now I want to pick'12'
so:
NSString *t=#"Mytest12test";
NSString *x=[t substringWithRange:NSMakeRange(6, 2)] ;
In your code instead of length you are passing index of end character that is your mistake.
I don't know why your are using this approach, but iOS provides a string function which separates a string with respect to another string and returns an array of the components. See the following example:
NSString * str = #"dadsada/2/dsadsa";
NSArray *listItems = [str componentsSeparatedByString:#"/"];
NSString *component = [listItems objectAtIndex:1];
Now your component string should have 2 store in it.
When the compiler runs into this code...
else{
end = i + 1;
}
... in the last iteration of the loop, it sets the end variable to one more then the range of MYSTRING. This is why you are getting that error. To fix it, just do this:
else{
end = i;
}
Hope this helps!
P.S. Saleh's approach is a simpler way of accomplishing what you want
------UPDATE------
You should do it like this actually:
NSMutableArray *occurencesOfSlashes = [[NSMutableArray alloc] init];
char looking = '/';
for(int i=0; i < MYSTRING.length; i++){
if ([MYSTRING characterAtIndex:i] == looking) {
[occurencesOfSlashes addObject:[NSNumber numberWithInt:i]];
}
NSString *finalString = [MYSTRING substringWithRange:NSMakeRange([occurencesOfSlashes objectAtIndex:0],[occurencesOfSlashes objectAtIndex:1])];

CS193p-Adding backspace to a calculator

I recently started following the online course on iPhone development from Stanford University on iTunes U.
I'm trying to do the homework assignments now for the first couple of lectures. I followed through the walkthrough where I built a basic calculator, but now I'm trying the first assignment and I can't seem to work it out. It's a follows:
Implement a “backspace” button for the user to press if they hit the wrong digit button. This is not intended to be “undo,” so if they hit
the wrong operation button, they are out of luck! It’s up to you to
decided how to handle the case where they backspace away the entire
number they are in the middle of entering, but having the display go
completely blank is probably not very user-friendly.
I followed this: Creating backspace on iOS calculator
So the code is
-(IBAction)backspacePressed:(UIButton *)sender {
NSMutableString *string = (NSMutableString*)[display text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
[display setText:[NSString stringWithFormat:#"%#",temp]];
}
My question is shouldn't I check whether my last is a digit or operand? If operand, no execution and if digit, remove it...
First of all, there are several unnecessary steps in that code... And to answer your question, yes, you should check for an operand. Here is how I would write that method with a check:
NSString *text = [display text];
int length = [text length];
unichar c = [text characterAtIndex:length];
NSCharacterSet *digits = [NSCharacterSet decimalCharacterSet];
if ([digits characterIsMember:c] || c == '.') {
NSString *temp = [[display text] substringToIndex:length-1];
[display setText:temp];
}
I'm also going through the fall 2011 class on iTunes U.
The walk through gives us an instance variable userIsInTheMiddleOfEnteringANumber so I just checked to see if that is YES.
- (IBAction)backspacePressed {
if (self.userIsInTheMiddleOfEnteringANumber) {
if ([self.display.text length] > 1) {
self.display.text = [self.display.text substringToIndex:[self.display.text length] - 1];
} else {
self.display.text = #"0";
self.userIsInTheMiddleOfEnteringANumber = NO;
}
}
}
I used the approach taken by Joe_Schmoe, which is straightforward. (just remove characters in the dispaly until you reach the end).
If the user continues pressing 'Clear Error', I removed an item from the stack as well.
I have just started on the course myself, this post is quite old now but my solution might help others, food for thought if nothing else:
- (IBAction)deletePressed:(id)sender
{
NSString *displayText = [display text];
int length = [displayText length];
if (length != 1) {
NSString *newDisplayText = [displayText substringToIndex:length-1];
[display setText:[NSString stringWithFormat:#"%#",newDisplayText]];
} else {
userIsInTheMiddleOfEnteringANumber = NO;
NSString *newDisplayText = #"0";
[display setText:[NSString stringWithFormat:#"%#",newDisplayText]];
}
}

Create random string of characters, with rules

I would like to know the best way to create a random string of characters,
but with some simple rules.
for example:
( User defined length, may only contain one E, may only contain 2-4 'S' )
This would part of a Mac OSX app, and the User defined items would be in UI.
User sets parameters and presses "Generate" button.
The output is displayed in a NSTextField.
Of course I think I can handle the UI part, only noted incase someone wants to include sample code.
Thanks.
This works, but be aware that theoretically, it might not terminate. You might want to consider replacing extraneous Es and Ss with other letters to force it to terminate.
It would definitely loop forever if the user inputted length was 2!
BOOL canQuit = NO;
while (!canQuit)
{
NSMutableString *output = [[[NSMutableString alloc] init] autorelease];
while ([output length] < userDefinedLength)
{
//Generates a random character between a and z;
char c = ((arc4random() % (122 - 96)) + 97);
[output appendFormat:#"%c", c];
}
NSLog(#"%#", output);
int numberOfE = [output replaceOccurrencesOfString:#"e" withString:#"e" options:NSCaseInsensitiveSearch range:NSMakeRange(0, output.length)];
int numberOfS = [output replaceOccurrencesOfString:#"s" withString:#"s" options:NSCaseInsensitiveSearch range:NSMakeRange(0, output.length)];
canQuit = (numberOfE <= 1 && numberOfS >= 2 && numberOfS <= 4);
}

Weird cocoa bug?

Hey folks, beneath is a piece of code i used for a school assignment.
Whenever I enter a word, with an O in it (which is a capital o), it fails!
Whenever there is one or more capital O's in this program, it returns false and logs : sentence not a palindrome.
A palindrome, for the people that dont know what a palindrome is, is a word that is the same read left from right, and backwards. (e.g. lol, kayak, reviver etc)
I found this bug when trying to check the 'oldest' palindrome ever found: SATOR AREPO TENET OPERA ROTAS.
When I change all the capital o's to lowercase o's, it works, and returns true.
Let me state clearly, with this piece of code ALL sentences/words with capital O's return false. A single capital o is enough to fail this program.
-(BOOL)testForPalindrome:(NSString *)s position:(NSInteger)pos {
NSString *string = s;
NSInteger position = pos;
NSInteger stringLength = [string length];
NSString *charOne = [string substringFromIndex:position];
charOne = [charOne substringToIndex:1];
NSString *charTwo = [string substringFromIndex:(stringLength - 1 - position)];
charTwo = [charTwo substringToIndex:1];
if(position > (stringLength / 2)) {
NSString *printableString = [NSString stringWithFormat:#"De following word or sentence is a palindrome: \n\n%#", string];
NSLog(#"%# is a palindrome.", string);
[textField setStringValue:printableString];
return YES;
}
if(charOne != charTwo) {
NSLog(#"%#, %#", charOne, charTwo);
NSLog(#"%i", position);
NSLog(#"%# is not a palindrome.", string);
return NO;
}
return [self testForPalindrome:string position:position+1];
}
So, is this some weird bug in Cocoa?
Or am I missing something?
B
This of course is not a bug in Cocoa, as you probably knew deep down inside.
Your compare method is causing this 'bug in Cocoa', you're comparing the addresses of charOne and charTwo. Instead you should compare the contents of the string with the isEqualToString message.
Use:
if(![charOne isEqualToString:charTwo]) {
Instead of:
if(charOne != charTwo) {
Edit: tested it in a test project and can confirm this is the problem.
Don't use charOne != charTwo
Instead use one of the NSString Compare Methods.
if ([charOne caseInsensitiveCompare:charTwo] != NSOrderedSame)
It may also have to do with localization (but I doubt it).

I want to insert the line-feed character in the specified number of characters

Objective-C::
I want to insert the line-feed character in the specified number of characters.
Please teach when knowing.
for example
NSString str = #"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
?????? // -> #"aaaaa\naaaaa\naaaaa\n......"
No, apparently I don't have anything better to do on a Friday night than to answer random ancient "my tags" questions asked by people who were never that interested in the first place and have anyway long since departed SO.
-(NSString*)breakString:(NSString*)str everyNCharacters:(NSUInteger)n withDelimiter:(NSString*)delimiter
{
NSUInteger numBreaks = ([str length] / n) - (([str length] % n == 0) ? 1 : 0);
if ( numBreaks < 1 )
return str;
NSMutableString* result = [NSMutableString stringWithCapacity:([str length] + [delimiter length] * numBreaks)];
for ( int i = 0; i < numBreaks; ++i )
{
[result appendFormat:#"%#%#", [str substringWithRange:NSMakeRange(i * n, n)], delimiter];
}
[result appendString:[str substringFromIndex:(n * numBreaks)]];
return result;
}
In the specific case of the question, call thus:
NSString* answer = [arbitraryObjectContainingTheAboveMethod breakString:str everyNCharacters:5 withDelimiter:#"\n"];
Time for bed, said Zebedee.