2012-10-23 23 views
0

我嘗試掃描一個字符串並將其分割爲單獨的字符串。 我的代碼是:爲什麼我無法使用空格掃描整個字符串?

#import <Foundation/Foundation.h> 
NSArray *wordsArray; 
int amount; 
char input[80]; 
int main (int argc, const char * argv[]) 
{ 

    @autoreleasepool { 
     NSString *stra=[[NSString alloc] initWithString:@""];   

    // [email protected]"this is my sentence"; 
     NSLog(@"Please Enter a sentence!"); 
     scanf("%s",&input); 
     stra=[NSString stringWithCString:input encoding:NSASCIIStringEncoding]; 
    // NSLog(@"words: %@",str); 

     wordsArray = [stra componentsSeparatedByString:@" "]; 
     amount= [wordsArray count]; 
     NSLog(@"Number of Shows : %d", amount); 

     for (int i=0; i<amount; i++) 
     { 
      NSString *subString = [wordsArray objectAtIndex:i]; 
      NSLog(@"\n %@",[subString uppercaseString]); 
     } 


    } 
    return 0; 
} 

在輸入上: 「Test1的TEST2 TEST3」

我得到:Test1的

代碼不考慮空間。我如何掃描大廳字符串?

回答

1

這不起作用的一個原因是scanf沒有要查找的字符串大小,所以它停在第一個空白處。您可以使用的另一種方法是輸入的fgets()。
這裏的鏈接提供了更多的信息(我知道它說c,但你在這裏使用c函數) Allowing white spaces c