手记

Objective-c 中scanf 在循环中的使用问题及解决方法

有的时候, 在循环中scanf获取用户输入的数据时会遇到 scanf只被执行一次,第二次执行时就直接跳过去不执行的情况。在这种情况下严重的会导致程序无限死循环进尔导致程序崩溃。

出现该问题时, 解决方式是在scanf语句前加上 rewind(stdin)。
比如:

    do {
        NSLog(@"请输入你要观看的电影编号:");
        option = self.scanInputInt;
    }while(option == -1);

//scanInputint 方法:
-(int)scanInputInt {
    int userInput = -1;
    rewind(stdin);
    scanf("%d", &userInput);
    if (userInput != -1) {

    }else {
        NSLog(@"输入错误请重新输入\n");
        return -1;
    }
    return userInput;
}
1人推荐
随时随地看视频
慕课网APP