2012-10-31 40 views

回答

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); 
0
 scanf("%s",str); 
     mystr = [NSString stringWithUTF8String:str]; 
0

可以使用C庫函數scanf閱讀從標準輸入C字符串,然後創建從一個NSStringinitWithCString:encoding:

+0

我看看那個方法,但不知道要放什麼東西在編碼:位? – user1628311

+0

使用'NSUTF8StringEncoding'作爲典型案例。看看有關[創建字符串]的文檔(https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html) – waldrumpus

0

以下兩個字符串函數使用一個:

#include <stdio.h> 

char *fgets(char * restrict str, int size, FILE * restrict stream); 

char *gets(char *str); 

使用gets是簡單的,但它是不安全的生產代碼中使用。下面是使用fgets一個例子:

#define MAX_LENGTH 80 

- (void)example 
{ 
    char buf[MAX_LENGTH]; 
    fgets(buf, MAX_LENGTH, stdin); 

    NSString *s = [NSString stringWithUTF8String:buf]; 
    NSLog(@"%@", s); 
} 
相關問題