isEqualToString 不返回 true
即使您在运行程序时键入“stop”,“Stopping”语句也永远不会被打印。 initWithUTF8String:
方法是否引入了额外的格式?
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
char holderText[256];
fgets(holderText, 256, stdin);
NSString *words = [[NSString alloc] initWithUTF8String:holderText];
if ([words isEqualToString:@"stop"]) {
NSLog(@"STOPPING");
}
NSLog(@"This is what you typed: %@", words);
[pool drain];
return 0;
}
The "Stopping" statement never gets printed even if you type 'stop' when running the program. Is the initWithUTF8String:
method introducing extra formatting?
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
char holderText[256];
fgets(holderText, 256, stdin);
NSString *words = [[NSString alloc] initWithUTF8String:holderText];
if ([words isEqualToString:@"stop"]) {
NSLog(@"STOPPING");
}
NSLog(@"This is what you typed: %@", words);
[pool drain];
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fgets
将在它提供给您的字符串中包含尾随换行符(除非它不适合缓冲区,但这里不是这样),所以它将是"stop\ n"
而不是"stop"
。将日志行更改为:
希望能够清楚地表明发生了什么。
修改比较以考虑到这一点,或者在比较之前删除换行符。
fgets
will include the trailing newline in the string it gives you (except in the case where it wouldn't fit in the buffer but that's not so here), so it will be"stop\n"
rather than"stop"
.Changing the log line to:
should hopefully make it clear what's happening.
Either modify the comparison to take this into account, or trim the newline off before comparing.
由于
fgets
可能会包含尾随换行符,因此您可能需要使用stringByTrimmingCharactersInSet:
修剪字符串中的所有换行符:Since
fgets
will probably include a trailing newline, you might want to do a trim of all newlines in the string by usingstringByTrimmingCharactersInSet:
:即使您泄漏了
words
字符串,代码看起来也很好。您需要在该分配调用的末尾添加一个[autorelease]
。您可以尝试
initWithCString
并修剪新行和周围的空白。The code looks fine, even though you're leaking the
words
string. You need to add an[autorelease]
on the end of that alloc call.You could try
initWithCString
and also trim new lines and surrounding whitespace.