使用while循环和数组时需要的基本说明

时间:2016-10-18 17:38:54

标签: arrays string while-loop puts

// 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");


}

你好,我基本上是在尝试打印所有男性名字,然后打印女性名字(我还没有做那部分)。下面的代码确实有效,但我发现很难理解它是如何工作的。比如,例如我不理解它所说的部分(情侣[I] [j]!='')。如果我试图用空格标记分割字符串,为什么它不等于空格。我很感激人们可能提供的任何帮助和解释!谢谢!

1 个答案:

答案 0 :(得分:2)

&#39;每一对&#39;可以被视为一个字符串(即一个字符数组),由两个名字组成 - 一个男性,一个女性 - 由一个空格字符分隔。 &#39; while&#39;循环是将对的男性名称复制到单独的数组&#39;男性,一次一个字符。 &#39; while&#39;的预期行动。循环是为了保持复制字符直到遇到分隔空间,然后放入&#39; \ 0&#39;标记复制的男性名称字符串的结尾。但是&#39;而&#39;只要某些条件成立,就意味着这样做,所以你想要成真的条件就是空间ISN&#39; T现在正在看的角色。在第一行“夫妇”中执行你头脑中的代码,如下所示:

a) i=0 and j=0 and enter the 'while' loop:
b) couples[i][j] = 'J'.  Is 'J' != ' ' ? --> YES, copy 'J' to males[0][0], increment j
c) couples[i][j] = 'o'.  Is 'o' != ' ' ? --> YES, copy 'o' to males[0][1], increment j
d) couples[i][j] = 'h'.  Is 'h' != ' ' ? --> YES, copy 'h' to males[0][2], increment j
e) couples[i][j] = 'n'.  Is 'n' != ' ' ? --> YES, copy 'n' to males[0][3], increment j
f) couples[i][j] = ' '.  Is ' ' != ' ' ? --> NO, copy '\0' to males[0][4], reset j to 0