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);
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.
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);
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 .)
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.
This is how I'd do it:
char word [40];
scanf("%s",word);
NSString * userInput = [[NSString alloc] initWithCString: word encoding: NSUTF8StringEncoding];
scanf does not work with NSString as scanf doesn’t work on objects. It works only on primitive datatypes such as:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With