【问题标题】:How can I print multiple rows of multiple matrixes in C?如何在 C 中打印多行多个矩阵?
【发布时间】:2021-09-25 05:06:24
【问题描述】:

我需要接收N个名字、城市和能力,然后打印出来。

这是我目前所拥有的,我不知道为什么它不起作用:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int N, i, j;
  scanf("%d %d", &N);
  char name[i][10];
  char city[i][100];
  int abiliity[i][100];

  for (i = 0; i < N; ++i) {
    scanf("%s %s %d", name[i], city[i], &abiliity[i]);
  }

  for (i = 0; i < N; i++) {
    for (j = 0; j < 1000; j++) {
      printf("%c %c %d\n", name[i][j], city[i][j], abiliity[i][j]);
    }
  }

  return 0;
}

【问题讨论】:

  • char name[i][10]; 您的数组声明具有未定义的行为,因为它们使用了未初始化的变量 i。改为使用N
  • for(j=0;j&lt;1000;j++){ 这没有任何意义。当您的数组中显然没有那么多字符时,为什么要使用1000?因此,这也会导致未定义的行为,因为它会溢出缓冲区。而且从每个数组中打印一个字符也没有意义 - 结果将是每个字符串中的交错字符。改用%s 打印整个字符串。
  • 请解释您对char name[i][10];for(j=0;j&lt;1000;j++) 的理由。我同意 kaylums 对此的看法,但我想知道这种怪异的原因。如果您描述您的推理,我们也许能够查明您的问题的根源。否则,该问题给人的印象是显示随机拼凑的代码片段并要求“修复”从未真正在理解基础上编写的东西。我倾向于以不可重现的方式结束这个问题。
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: c string matrix vector


【解决方案1】:
#include <stdio.h>

int main() {
    int N, i;
    printf("N:");
    scanf("%d", &N); //you only need one %d
    char name[N][10]; //put here N instead of i
    char city[N][100]; //put here N instead of i
    int ability[N]; //put here N instead of i. It's not a string, so you don't need a 2D array

    printf("type %d times the name, city and ability\n", N);
    for (i = 0; i < N; ++i) {
        scanf("%s %s %d", name[i], city[i], &ability[i]);

    }

    for (i = 0; i < N; i++) {
        //you don't need the second for loop if you use %s
        printf("%s %s %d\n", name[i], city[i], ability[i]);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2013-07-03
    • 2014-03-22
    • 1970-01-01
    • 2015-03-15
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多