I'm just creating a simple program that gets user input then prints it back in the terminal. I don't know how to get the user input as an NSString. I've read about scanf() in C but that doesn't seem to be able to take strings. I was wondering if there is a possible way to do it?
Asked
Active
Viewed 1.1k times
4 Answers
0
You can use the C library function scanf
to read a C string from the standard input, and then create an NSString
from that with initWithCString:encoding:
.

waldrumpus
- 2,540
- 18
- 44
-
I had a look at the that method but didn't know what to put in the encoding: bit? – user1628311 Oct 31 '12 at 11:34
-
Use `NSUTF8StringEncoding` for the typical cases. Have a look a the documentation about [Creating strings](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html) – waldrumpus Oct 31 '12 at 11:35
0
printf("Enter your string: ");
scanf("%s", str); // read and format into the str buffer
printf("Your string is %s\n", str); // print buffer
// you can create an NS foundation NSString object from the str buffer
NSString *lastName = [NSString stringWithUTF8String:str];
// %@ calls description o object - in NSString case, prints the string
NSLog(@"lastName=%@", lastName);

Abdul
- 48
- 4
-
Personally wouldn't recommend using scanf for buffer reasons in situations where user types excessive characters. – Ndong Akwo Apr 21 '18 at 00:23
0
Use one of the following two string functions:
#include <stdio.h>
char *fgets(char * restrict str, int size, FILE * restrict stream);
char *gets(char *str);
Using gets
is simpler, but it's unsafe for use in production code. Here's an example using fgets
:
#define MAX_LENGTH 80
- (void)example
{
char buf[MAX_LENGTH];
fgets(buf, MAX_LENGTH, stdin);
NSString *s = [NSString stringWithUTF8String:buf];
NSLog(@"%@", s);
}

jlehr
- 15,557
- 5
- 43
- 45