【发布时间】:2016-10-18 17:38:53
【问题描述】:
// ConsoleApplication27.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include <string.h>
void main()
{
char couples[5][50] = { "John Nora", "Paul Kathy", "Tom Claire", "Martin Mary", "Tony Teresa" };
char male[5][51];
char female[5][51];
int i;
int j = 0;
printf("Males: ");
for (i = 0; i < 5; i++)
{
while (couples[i][j] != ' ')
{
male[i][j] = couples[i][j];
j++;
}
male[i][j] = '\0';
puts(male[i]);
j = 0;
}
printf("\n");
}
您好,我实际上是在尝试打印所有男性姓名,然后打印女性姓名(我还没有完成那部分)。下面的代码确实有效,但我只是发现很难理解它是如何工作的。例如,我不明白它所说的部分 while(couples[I][j] != ' ').如果我试图用空格标记分割字符串,为什么它不等于空格。我将不胜感激人们可能有的任何帮助和解释!谢谢!
【问题讨论】:
-
while在遇到空格时停止(因为' ' != ' '为假),但复制它之前的所有内容(因为除了空格!= ' '之外的任何字符都为真)。此外,main()应该返回int,而不是void;void main()是一个扩展,并不是每个编译器都支持。 -
谢谢,你知道我为什么要把 j 加 1 吗?
-
那是因为
i是每个 C 字符串的索引,j是字符串中每个字符的索引。例如,couples[0]是"John Nora",并且:couples[0][0]是'J',couples[0][1]是'o',couples[0][2]是'h',等等。 -
谢谢,我真的很感激!
标签: arrays string while-loop puts