【问题标题】:Using loops with arrays in C在 C 中使用带有数组的循环
【发布时间】:2017-03-04 05:17:34
【问题描述】:
#include <stdio.h>    

void main()
{
    char couples[3][50] = { "Paul Kathy", "John Nora", "Martin Mary" };
    char husbands[3][50];
    char wives[3][50];  
    int i = 0;
    int j = 0;

    puts("Husbands: ");
    for (i = 0; i < 3; i++)
    {
        while (couples[i][j] != ' ')
        {
            couples[i][j] = husbands[i][j];
            j++;
        }
        husbands[i][j] = '\0';
        puts(husbands[i]);
        j = 0;
    }

}

我之前创建了一个类似的程序,并且运行良好。然而,虽然这确实构建和编译成功,但它不能正确运行。本质上,我试图根据空格字符将情侣分成一个单独的字符串。我做错了什么?

【问题讨论】:

  • main 有两个有效签名:int main (void)int main (int, char **)。应该避免任何以其他方式教你的文学作品。寻求更好的学习材料,掌握 C 的基础知识并不难。
  • “运行不正确”?它有什么作用?
  • 请参阅What should main() return in C and C++,了解允许和不允许的全部细节。允许void main() 的平台数量很少。

标签: c arrays string loops char


【解决方案1】:

尝试一些简单的事情。 sscanf() 函数可以很容易地从字符串中提取数据:

#include <stdio.h>

int main(void)
{
    char couples[3][50] = { "Paul Kathy", "John Nora","Martin Mary" };
    char husbands[3][50];
    char wives[3][50];  
    int i = 0;

    for (i = 0; i < 3; i++)
    {
        /* Extract husband and wife names. You know they are separated by a space. */
        sscanf(couples[i], "%s %s", husbands[i], wives[i]);
    }
}

原代码中的问题包括:

  1. Couple 字符串被未初始化的丈夫字符串覆盖。

  2. 不提取妻子姓名。

【讨论】:

  • 您应该解释您在做什么(并删除不应该出现在原始问题中的样板评论)。您还应该解释原始代码有什么问题——为什么它不能正常工作。
  • @JonathanLeffler 感谢您的反馈。我已经更新了我的答案。请检查它。
【解决方案2】:

这是你的问题:

couples[i][j] = husbands[i][j];

您将husbands 分配给couples,而不是您需要的其他方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多