c++ - 遍历还包含未使用元素的字符串数组

标签 c++ arrays for-loop initialization c-strings

问题:我只想打印数组 names 中定义的三个元素,而不更改我定义的数组大小。该程序目前打印出这三个元素,但在遍历所有 20 个元素时还会打印出 17 行新行。

问题:当检查不具有至少一个字符的值的元素时,我如何以及在哪里创建一个条件来跳出循环?换句话说,我如何不打印出额外的十七行?

#include <stdio.h>
#define MAX_I 20
#define MAX_J 20

int main() {
    char names[MAX_I][MAX_J] = {"Foo", "Bar", "Baz"};

    // First example
    printf("Example 1:\n");
    for (int i = 0; i < MAX_I; i++) {
        for (int j = 0; j < MAX_J; j++) {
            printf("%c", names[i][j]);
        }
        printf("\n");
    }

    // Second example
    printf("\nExample 2:\n");
    for (char* iter : names) {
        printf("%s\n", iter);
    }
}

最佳答案

空 C 字符串的第一个(也是唯一一个!)元素设置为 '\0'(也称为 0)。

您的数组声明将对剩余元素进行零初始化,因此您可以依赖此规则。

因此:

#include <stdio.h>
#define MAX_I 20
#define MAX_J 20

int main() {
    char names[MAX_I][MAX_J] = {"Foo", "Bar", "Baz"};

    // First example
    printf("Example 1:\n");
    for (int i = 0; i < MAX_I; i++) {

        // *** This block is new ***
        if (names[i][0] == '\0')
        {
           // Empty string! Skip this, and all following
           break;
        }

        for (int j = 0; j < MAX_J; j++) {

            // *** This block is new ***
            if (names[i][j] == '\0')
            {
               // End of string!
               break;
            }

            printf("%c", names[i][j]);
        }
        printf("\n");
    }

    // Second example
    printf("\nExample 2:\n");
    for (char* iter : names) {

        // *** This block is new ***
        if (iter[0] == '\0')
        {
           // Empty string! Skip this, and all following
           break;
        }

        printf("%s\n", iter);
    }
}

请注意,在您的第一个示例中,我还冒昧地跳过打印尾随空值。

关于c++ - 遍历还包含未使用元素的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59723828/

相关文章:

c++ - 如何使用 mpl 技术启用构造函数

c++ - 对包含 k 个已排序部分的 n 个元素的数组进行排序

c++ - 一些比普通循环和设置更快地分配和初始化数组的方法

c - fgets 在 C 中导致无限循环

c++ - static_cast 限制对公共(public)成员函数的访问?

c++ - Visual C++ 的调用方法

c - 我怎样才能在 C 中做到这一点?

python - 循环遍历 pandas Dataframe 以从另一个 Dataframe 获取值

c++ - 如何 Hook 时间功能

php - 获取 mysql_fetch_array 中的下一行