将 scanf 与 NSString 一起使用
我希望用户输入一个字符串,然后将输入分配给 NSString。现在我的代码如下所示:
NSString *word;
scanf("%s", &word);
I want the user to input a string and then assign the input to an NSString. Right now my code looks like this:
NSString *word;
scanf("%s", &word);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
scanf 函数读入一个 C 字符串(实际上是一个 char 数组),像这样:
您可以将 char 数组转换为 NSString,如下所示:
但是 scanf 仅适用于控制台(命令行)程序。如果您尝试在 Mac 或 iOS 设备上获取输入,则不需要使用 scanf 来获取用户输入。
The scanf function reads into a C string (actually an array of char), like this:
You can convert a char array into NSString like this:
However scanf only works with console (command line) programs. If you're trying to get input on a Mac or iOS device then scanf is not what you want to use to get user input.
scanf
不适用于任何对象类型。如果您有一个 C 字符串并希望从中创建一个 NSString,请使用-[NSString initWithBytes:length:encoding:]
。scanf
does not work with any object types. If you have a C string and want to create an NSString from it, use-[NSString initWithBytes:length:encoding:]
.scanf 不适用于 NSString,因为 scanf 不适用于对象。它仅适用于基本数据类型,例如:
做什么?
从技术上讲,字符串由一系列单独的字符组成。因此,要接受字符串输入,您可以读取字符序列并将其转换为字符串。
使用:
这是一个工作示例:
这是对上述代码的解释,逐条注释:
运行您的项目;如果您输入一个单词并按 Enter 键,程序应该打印出您输入的相同单词。只要确保单词少于 40 个字符即可;如果输入过多,可能会导致程序崩溃——欢迎您亲自测试一下! :]
摘自:RW。
scanf does not work with NSString as scanf doesn’t work on objects. It works only on primitive datatypes such as:
What to do?
Technically a string is made up of a sequence of individual characters. So to accept string input, you can read in the sequence of characters and convert it to a string.
use:
Here is a working example:
Here’s an explanation of the above code, comment by comment:
Run your project; if you enter a word and hit Enter, the program should print out the same word you typed. Just make sure the word is less than 40 characters; if you enter more, you might cause the program to crash — you are welcome to test that out yourself! :]
Taken from: RW.
我就是这样做的:
This is how I'd do it:
是的,但是 sscanf 可以,并且可能是复杂 NSString 解析的一个很好的解决方案。
yes, but sscanf does, and may be a good solution for complex NSString parsing.
简单的解决方案是
Simple Solution is
也许这对您有用,因为它也接受带空格的字符串。
Maybe this will work for you because it accepts string with spaces as well.
NSFileHandle 类是文件描述符的面向对象包装器。对于文件,您可以在文件内读取、写入和查找。
The NSFileHandle class is an object-oriented wrapper for a file descriptor. For files, you can read, write, and seek within the file.