Using scanf with NSStrings

I want the user to input a string and then assign the input to an NSString. Right now my code looks like this:

NSString *word; 

scanf("%s", &word);

Solution 1:

The scanf function reads into a C string (actually an array of char), like this:

char word[40];

int nChars = scanf("%39s", word);   // read up to 39 chars (leave room for NUL)

You can convert a char array into NSString like this:

NSString* word2 = [NSString stringWithBytes:word 
                                     length:nChars
                                   encoding:NSUTF8StringEncoding];

However scanf only works with console (command line) programs. If you're trying to get input on a Mac or iOS device then scanf is not what you want to use to get user input.

Solution 2:

scanf does not work with any object types. If you have a C string and want to create an NSString from it, use -[NSString initWithBytes:length:encoding:].

Solution 3:

scanf does not work with NSString as scanf doesn’t work on objects. It works only on primitive datatypes such as:

  1. int
  2. float
  3. BOOL
  4. char

What to do?

Technically a string is made up of a sequence of individual characters. So to accept string input, you can read in the sequence of characters and convert it to a string.

use:

[NSString stringWithCString:cstring encoding:1];

Here is a working example:

NSLog(@"What is the first name?");
char cstring[40];
scanf("%s", cstring);

firstName = [NSString stringWithCString:cstring encoding:1];

Here’s an explanation of the above code, comment by comment:

  1. You declare a variable called cstring to hold 40 characters.
  2. You then tell scanf to expect a list of characters by using the %s format specifier.
  3. Finally, you create an NSString object from the list of characters that were read in.

Run your project; if you enter a word and hit Enter, the program should print out the same word you typed. Just make sure the word is less than 40 characters; if you enter more, you might cause the program to crash — you are welcome to test that out yourself! :]

Taken from: RW.

Solution 4:

This is how I'd do it:

char word [40];
scanf("%s",word);

NSString * userInput = [[NSString alloc] initWithCString: word encoding: NSUTF8StringEncoding];