Ask user for information and return that information - objective-c

I am trying to ask the user to enter their name and then return; "Hello and their name". I know its something simple that I am missing, but I just dont know what it is.
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSString * name = #"";
NSLog(#"What is your name?");
scanf("%#", &name);
NSLog(#"Hello %#",name);
}
}

You're trying to mix Objective-C and C here. This is somewhat tricky to do, but let me see if I can help point you the right direction.
First, change:
NSString * name = #"";
scanf("%#", &name);
to:
char name[64];
scanf("%s", &name);
and see if that works better.
scanf is a C function that works with c types, and NSString is an objective C object which doesn't really work with "scanf".
(The "64" means that there's enough buffer space for 64 characters and if you blow past that, the app will likely crash).
Also, change:
NSLog(#"Hello %#",name);
to this:
NSLog(#"Hello %s",name);
As "%s" in the format tells NSLog that you're passing a C-style string and not a NSString object.

You're using an NSString object in C, which doesn't work. scanf expects a C string. Here's an example:
NSLog(#"What is your name?");
char name[40];
scanf("%s", name);
NSLog(#"Hello %#",[NSString stringWithCString:name encoding:NSUTF8StringEncoding]);
Or you can stay 100% in C:
printf("What is your name?");
char name[40];
scanf("%s", name);
printf("Hello %s", name);

Related

objective-c right padding

hello all hope someone can help with that. I was browsing the net and nothing really seems to make sense :S
so I have a string lets say:
"123" and I would like to use a function like:
padr("123", 5, 'x')
and the result should be:
"123xx"
Sorry but Objective-C is a nightmare when dealing with strings :S
You could create your own method to take the initial string, desired length, and padding character (as I was starting to do & also described in a few similar questions)
Or you could use the NSString method Apple already provides ;)
NSString *paddedString = [#"123"
stringByPaddingToLength: 5
withString: #"x" startingAtIndex:0];
See NSString Class Reference for this method.
What about the NSString method stringByPaddingToLength:withString:startingAtIndex:.
NSString* padr(NSString* string, NSUInteger length, NSString *repl)
{
return [string stringByPaddingToLength:length withString:repl startingAtIndex:0];
}
NSMutableString* padString(NSString *str, int padAmt, char padVal)
{
NSMutableString *lol = [NSMutableString stringWithString:str];
while (lol.length < padAmt) {
[lol appendFormat:#"%c", padVal];
}
return lol;
}
And the Call
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSLog(#"%#", padString(#"123", 5, 'x'));
}
return 0;
}

How to read input in Objective-C?

I am trying to write some simple code that searches two dictionaries for a string and prints to the console if the string appears in both dictionaries. I want the user to be able to input the string via the console, and then pass the string as a variable into a message. I was wondering how I could go about getting a string from the console and using it as the argument in the following method call.
[x rangeOfString:"the string goes here" options:NSCaseInsensitiveSearch];
I am unsure as to how to get the string from the user. Do I use scanf(), or fgets(), into a char and then convert it into a NSSstring, or simply scan into an NSString itself. I am then wondering how to pass that string as an argument. Please help:
Here is the code I have so far. I know it is not succinct, but I just want to get the job done:
#import <Foundation/Foundation.h>
#include <stdio.h>
#include "stdlib.h"
int main(int argc, const char* argv[]){
#autoreleasepool {
char *name[100];
printf("Please enter the name you wish to search for");
scanf("%s", *name);
NSString *name2 = [NSString stringWithFormat:#"%s" , *name];
NSString *nameString = [NSString stringWithContentsOfFile:#"/usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
NSString *dictionary = [NSString stringWithContentsOfFile:#"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];
NSArray *nameString2 = [nameString componentsSeparatedByString:#"\n"];
NSArray *dictionary2 = [dictionary componentsSeparatedByString:#"\n"];
int nsYES = 0;
int dictYES = 0;
for (NSString *n in nameString2) {
NSRange r = [n rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
nsYES = 1;
}
}
for (NSString *x in dictionary2) {
NSRange l = [x rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (l.location != NSNotFound){
dictYES = 1;
}
}
if (dictYES && nsYES){
NSLog(#"glen appears in both dictionaries");
}
}
}
Thanks.
Safely reading from standard input in an interactive manner in C is kind of involved. The standard functions require a fixed-size buffer, which means either some input will be too long (and corrupt your memory!) or you'll have to read in a loop. And unfortunately, Cocoa doesn't offer us a whole lot of help.
For reading standard input entirely (as in, if you're expecting an input file over standard input), there is NSFileHandle, which makes it pretty succinct. But for interactively reading and writing like you want to do here, you pretty much have to go with the linked answer for reading.
Once you have read some input into a C string, you can easily turn it into an NSString with, for example, +[NSString stringWithUTF8String:].

Why do i get "program received signal: "EXC_BAD_ACCESS" on NSString veriable

I just recently started learning Objective C, when i run the next program i get error
"program received signal: "EXC_BAD_ACCESS"
For the code line
if([*userChoice isEqualToString:#"yes"])
The full code is:
void initGame (void);
void restartGame(void);
void toGoOn(char *playerChoice);
int guess=-1;
int from=-1;
int to=-1;
bool playStatus=true;
bool gameStatus=true;
int answer=-1;
NSString *userChoice[10];
//if true the game is on
int main (int argc, const char * argv[])
{
#autoreleasepool {
GuessManager *game=GUESS;
NSLog(#"Hello, lets play");
NSLog(#"Please provide a positive range in which you would like to play");
do{
initGame();
[game setnumberToGuess:from :to];
do {
printf("Make you guess:");
scanf("%d", &guess);
[game setUserGuess:guess];
[game checkUserGuess];
if([game getDidIgetIt])
{
playStatus=false;
}
else
{
playStatus=true;
}
} while (playStatus);
restartGame();
}while(gameStatus);
printf("Thanks For Playing PanGogi Games! GoodBye");
}
return 0;
}
void initGame (void)
{
printf("from:");
scanf("%d",&from);
printf("to:");
scanf("%d",&to);
}
void restartGame(void)
{
printf("Would you like to continue?(yes/no)");
scanf("%s",&userChoice);
//scanf("%d",&answer);
// if(answer==1)
if([*userChoice isEqualToString:#"yes"])
{
gameStatus=true;
}
else
{
gameStatus=false;
}
}
I understand that its related to the NSString variable userChoice and how its used in
the if, but what i cant find is what am i doing wrong.
Please help :)
You have 3 errors in the code
1) I think you are getting confused with NSString and C style char array... You just need to use single NSString object to save multi character data..
NSString *userChoice;
2) Since you want to input data using scanf, you need a C style character array. scanf won't work with NSString types.
char tempArray[10];
int count = scanf("%s",&tempArray);
userChoice = [NSString stringWithBytes:tempArray length:count encoding: NSUTF8StringEncoding];
3) Now you can use NSString directly.. No need for pointer like syntax
if( [userChoice isEqualToString: #"yes"]){
.....
.....
}
You're using NSString as if it was char. It's not. It's a class that represents a string.
The scanf function is a C function and needs a char array, not an NSString.
char str[80];
scanf("%s", &str);
You can initialize an NSString object with a char array like this:
NSString *userChoice = [NSString stringWithCString:str encoding:NSASCIIEncoding];
And compare like this:
if ([userChoice isEqualToString:#"yes"]) {
...
} else {
...
}

function that returns a string

Silly as it may sound, I am trying to write a simple function in objective-c which returns a string and displays it, the following code nearly works but I can't get printf to accept the functions return value ...
NSString* getXMLElementFromString();
int main(int argc, char *argv[])
{
printf(getXMLElementFromString());
return NSApplicationMain(argc, (const char **) argv);
}
NSString* getXMLElementFromString() {
NSString* returnValue;
returnValue = #"Hello!";
return returnValue;
}
NSString* is not equivalent to a traditional C string, which is what printf would expect. To use printf in such a way you'll need to leverage an NSString API to get a null-terminated string out of it:
printf("%s", [getXMLElementFromString() UTF8String]);
You should instead use NSLog() which takes a string (or a format string) as a parameter.
You could use either
NSLog(getXMLElementFromString());
or
NSLog(#"The string: %#", getXMLElementFromString());
Where the %# token specifies an Objective-C object (in this case an NSString). NSLog() works essentially the same as printf() when it comes to format strings, only it will also accept the object token.
I don't know that printf can handle an NSString. Try somethign like:
printf ("%s\n", [getXMLElementFromString()cString]);

Very basic Objective-C/C Problem

Here's my code:
#import <Foundation/Foundation.h>
void PrintPathInfo() {
const char *path = [#"~" fileSystemRepresentation];
NSLog(#"My home folder is at '%#'", path);
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
PrintPathInfo();
[pool drain];
return 0;
}
And here's my problem:
Program received signal: “EXC_BAD_ACCESS”.
I really think the problem is my NSLog but I don't know how to solve it.
Could someone help me please? Thanks!
path is not an NSString, which is why that crashes. %# in a formatting string expects an object, and asks it for a description to get a string to print... because you are using a C style string, you need to use the standard C string formatters OR convert the const char * back to an NSString using the initWithCString:encoding: class method of NSString.
Staying with a const char *, you can use:
NSLog(#"My home folder is at '%s'", path);
which would work.
%# is for objects. (Like NSString). for const char* you will want the good old %s from the c's printf format codes.
See http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
For the format specifies and their meanings