【问题标题】:Objective C do while loop not exiting on false conditionObjective C do while循环在错误条件下不退出
【发布时间】:2015-09-24 15:41:38
【问题描述】:

在输入“done”之前,循环应该接受名称(并转换为 NSString),但它只是继续。根据类似问题的解决方案,我在循环中有两个不同的检查,但它们都不起作用。

NSMutableArray *names = [[NSMutableArray alloc] init];
char t[150];
NSString *str = @"";
do{
    printf("Input a name (enter \"DONE\" to exit)\n");
    fgets(t, 150, stdin);
    if (strcmp(t, "DONE") ==0)
        break;
    str = [NSString stringWithCString: t encoding: NSASCIIStringEncoding];
    if ([str caseInsensitiveCompare: @"DONE"] == NSOrderedSame)
        break;
    [names addObject: str];
} while ([str caseInsensitiveCompare: @"DONE"] != NSOrderedSame);

此外,当我将其更改为退出时 str not 等于“完成”时,循环成功退出。可能出了什么问题?
(我是 Objective C 的新手,所以如果答案很明显,我深表歉意。)

【问题讨论】:

  • 你确定程序真的进入了if语句吗?尝试使用调试器进行检查。可能是 if 语句返回 false。

标签: objective-c while-loop do-while


【解决方案1】:

fgets() 函数会给你一行输入,这一点很重要,包括尾随的换行符!

而且,由于DONE\nDONE 不同,它不会退出循环。

解决此问题的一种方法是自己删除换行符,例如:

fgets(t, 150, stdin);
size_t tlen = strlen (t);
if ((tlen > 0) && (t[tlen-1] == '\n'))
    t[tlen-1] = '\0';

或者,您可以删除行尾(包括换行符)的 all 空格,例如:

fgets(t, 150, stdin);
size_t tlen = strlen (t);
while ((tlen > 0) && isspace (t[tlen-1]))
    t[--tlen] = '\0';

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 2023-02-15
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多