开发者

Xcode scanf char count

开发者 https://www.devze.com 2023-04-12 06:06 出处:网络
I found out in Xcode command line tool you can enter int into the code yourself with scanf. When I tried this for a NS开发者_如何学JAVAString, it didn\'t worked, and I found out scanf returns an integ

I found out in Xcode command line tool you can enter int into the code yourself with scanf. When I tried this for a NS开发者_如何学JAVAString, 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];
...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号