回答
scanf
不適用於任何對象類型。如果你有一個C字符串並且想從它創建一個NSString,使用-[NSString initWithBytes:length:encoding:]
。
的scanf函數讀入一個C字符串(實際上字符數組),就像這樣:
char word[40];
int nChars = scanf("%39s", word); // read up to 39 chars (leave room for NUL)
您可以將字符數組轉換爲NSString的是這樣的:
NSString* word2 = [NSString stringWithBytes:word
length:nChars
encoding:NSUTF8StringEncoding];
然而 scanf僅適用於控制檯(命令行)程序。如果您嘗試在Mac或iOS設備上輸入內容,那麼scanf不是您想用來獲取用戶輸入的內容。
是的,但是sscanf可以,並且可能是複雜的NSString解析的一個很好的解決方案。
這是我會怎麼做它:
char word [40];
scanf("%s",word);
NSString * userInput = [[NSString alloc] initWithCString: word encoding: NSUTF8StringEncoding];
注意:您不需要放置'&'由於單詞不是指針,並且是實際的字符數組。 – ManOx 2012-10-30 17:19:24
scanf函數不NSString的工作作爲scanf函數不上對象。它僅適用於基本數據類型,如:
- INT
- 浮動
- BOOL
- 焦炭
怎麼辦?
從技術上說,一個字符串是由一系列單個字符組成的。因此,要接受字符串輸入,您可以讀取字符序列並將其轉換爲字符串。
使用:
[NSString stringWithCString:cstring encoding:1];
這裏是一個工作示例:
NSLog(@"What is the first name?");
char cstring[40];
scanf("%s", cstring);
firstName = [NSString stringWithCString:cstring encoding:1];
下面是上面代碼的說明,通過註釋評論:
- 您聲明一個變量稱爲CString的保存40個字符。
- 然後,您通過使用%s格式說明符告訴scanf期望一個字符列表。
- 最後,從被讀取的字符的列表中創建一個NSString對象
運行項目。如果你輸入一個單詞並按回車,程序應該輸出你輸入的同一個單詞。只要確保單詞少於40個字符;如果你輸入更多,你可能會導致程序崩潰 - 歡迎你自己測試一下!:]
攝影者:RW。
如果你使用'NSUTF8StringEncoding'作爲編碼選項,而不是'1',可能會更好理解。 – 2014-06-01 14:04:15
如何處理新的線條和空白? – anoop4real 2017-09-30 05:22:47
簡單的辦法就是
char word[40];
scanf("%39s", word);
NSString* word2 = [NSString stringWithUTF8String:word];
也許這會爲你工作,因爲它接受字符串的空間爲好。
NSLog(@"Enter The Name Of State");
char name[20];
gets(name);
NSLog(@"%s",name);
NSFileHandle類是文件描述符的面向對象的包裝器。對於文件,您可以在文件中讀取,寫入和查找。
NSFileHandle *inputFile = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [inputFile availableData];
NSString *word = [[NSString alloc]initWithData:inputData encoding:NSUTF8StringEncoding];
- 1. stringByAddingPercentEscapesUsingEncoding不能與'0'一起使用NSStrings
- 2. 使用Scanf與ObjC和iPhone
- 3. 比較NSStrings與Ä,Ö,Ü
- 4. 使用scanf與x86 GAS組件
- 5. 與scanf函數
- 6. 與scanf函數
- 7. 使用scanf()函數
- 8. 使用scanf函數
- 9. 使用scanf函數
- 10. scanf()與C++枚舉
- 11. 使用NSPredicate搜索NSStrings的範圍
- 12. 如何在使用while循環scanf後使用scanf!= EOF
- 13. 使用scanf動態分配()
- 14. 使用Scanf的問題?
- 15. 在scanf和printf中使用%
- 16. 使用scanf的錯誤
- 17. 使用scanf()和指針
- 18. 使用的scanf%P UB
- 19. 使用在scanf符號()
- 20. C:使用scanf的方法
- 21. 如何使用很多NSStrings保持內存使用率低,或者如何釋放NSStrings?
- 22. 問題與scanf函數
- 23. 故障與scanf函數(C)
- 24. 如何在控制檯應用程序中使用scanf而不使用scanf?
- 25. heightForRowAtIndexPath更長的NSStrings
- 26. 連接三個NSStrings
- 27. 泄漏NSStrings問題
- 28. 運行時異常與輸入使用scanf或獲取在C
- 29. 如何使用int16_t或int32_t與scanf函數
- 30. 需要幫助瞭解與scanf結合使用的ungetc行爲
如何創建c字符串?你可以編輯我的代碼,告訴我如何。 – Omar 2010-07-10 21:10:47
C字符串是一個字符數組,所以你只需寫'char word [100]'。 – 2012-09-23 10:17:03