【问题标题】:Basic explanation needed while using while loops and arrays使用 while 循环和数组时需要的基本解释
【发布时间】: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,而不是voidvoid 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


【解决方案1】:

“情侣”的每一行都可以被视为一个字符串(即一个字符数组),其中包含两个名字 - 一个男性,一个女性 - 由一个空格字符分隔。 'while' 循环将这对的男性姓名复制到单独的数组 'male' 中,一次一个字符。 'while' 循环的预期操作是继续复制字符直到遇到分隔空间,然后放入'\0' 以标记复制的男性姓名字符串的结尾。但是“while”的意思是“只要某些条件为真就这样做”,所以你想要为真的条件是空间不是现在正在查看的角色。在“情侣”的第一行执行你脑海中的代码,如下所示:

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

【讨论】:

    猜你喜欢
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2019-09-18
    • 2013-05-24
    相关资源
    最近更新 更多