Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 243
Omar Avatar asked Jul 10 '10 21:07

Omar


People also ask

How do I use scanf for pointers?

scanf() takes two inputs, first the format specifier and second a pointer to a variable. Hence, since you declare name as a pointer there is no need to redoit again by adding the & infront of the name. Remember that & is use to get the address - point to - of the variable.

Can we use scanf with pointers in C?

When you've used scanf() to input values, you've used the & operator to obtain the address of the variable that is to receive the input and used that as the argument to the function. When you have a pointer that already contains an address, you can use the pointer name as an argument. scanf(" %d", pvalue);

Can you buffer overflow scanf?

Fortunately, it is possible to avoid scanf buffer overflow by either specifying a field width or using the a flag. When you specify a field width, you need to provide a buffer (using malloc or a similar function) of type char * . (See Memory allocation, for more information on malloc .)

Does scanf take spaces?

We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds the first space. There are 4 methods by which the C program accepts a string with space in the form of user input.


2 Answers

This is how I'd do it:

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

NSString * userInput = [[NSString alloc] initWithCString: word encoding: NSUTF8StringEncoding];
like image 166
W.K.S Avatar answered Oct 22 '22 17:10

W.K.S


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.

like image 45
MarkP Avatar answered Oct 22 '22 16:10

MarkP