0

I found out in Xcode command line tool you can enter int into the code yourself with scanf. When I tried this for a NSString, it didn't worked, and I found out scanf returns an integer, so my question is, what do you use to enter a NSString and save it into a variable, like:

int number;
scanf("%i", &number);

EDIT: Now I found a code, but it only shows the first char:

char naamchar[40];
int nChars = scanf("%39s", naamchar);
NSString * naam = [[NSString alloc] initWithBytes:naamchar 
                                           length:nChars 
                                         encoding:NSUTF8StringEncoding];

naam is only 1 char :(

EDIT SOLUTION:

char naamchar[40];
scanf("%39s", naamchar);
NSString * naam = [NSString stringWithCString:naamchar encoding:NSUTF8StringEncoding];
...
Jeroen Bakker
  • 2,142
  • 19
  • 22
  • possible duplicate of [Using scanf with NSStrings](http://stackoverflow.com/questions/3220823/using-scanf-with-nsstrings) – PengOne Oct 10 '11 at 21:17
  • [`scanf`](http://en.wikipedia.org/wiki/Scanf) is a C function. As Objective-C is a superset of C, it also works there, but not with `NSObject`s (such as `NSString`) since these are not native to C. – PengOne Oct 10 '11 at 21:19
  • What are you trying to accomplish? – zaph Oct 10 '11 at 22:00

1 Answers1

0

man 3 scanf mentions:

These functions return the number of input items assigned.

nChars is set returning the number of items matched, in this case 1, not the number of characters in the string.

try replacing nChars with strlen(naamchar) i.e.

char naamchar[40];
int nChars = scanf("%39s", naamchar);
NSString * naam = [[NSString alloc] initWithBytes:naamchar 
                                       length:strlen(naamchar) 
                                     encoding:NSUTF8StringEncoding];

be sure to check for nChars == 0, which would indicate that there was no input to scan.