3
const char *sentence = "He was not in the cab at the time.";

printf("\"%s\" has %d spaces\n", sentence, (int) ^ {
    int i = 0;
     int countSpaces = 0;

    while (sentence[i] != '\0') {
        if (sentence[i] == 0x20) {
            countSpaces++;
        }
        i++;
    }    
    return countSpaces;
});

这段代码只计算字符串中的空格,但由于某种原因,它说的是 1606416608 个空格而不是 8 个。我不确定出了什么问题,所以感谢您的帮助!

4

1 回答 1

9

您将实际块传递给printf,而不是块的结果。相反,尝试

const char *sentence = "He was not in the cab at the time.";

printf("\"%s\" has %d spaces\n", sentence, (int) ^ {
    int i = 0;
    int countSpaces = 0;

    while (sentence[i] != '\0') {
        if (sentence[i] == 0x20) {
            countSpaces++;
        }
        i++;
    }    
    return countSpaces;
}()); // <-- note the extra parentheses here, indicating that you're calling the block
于 2012-06-16T19:27:12.040 回答