问题:我只想打印数组 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/