【问题标题】:how to take multiple strings as input and store them in a 2d array using c?如何将多个字符串作为输入并使用c将它们存储在二维数组中?
【发布时间】:2020-10-19 19:14:55
【问题描述】:

以下是我用 c 语言编写的代码,我试图将字符串作为输入并将它们存储在二维数组中。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
    int i,j,n;
    scanf("%d",&n);
    char a[n][n];
    for(i=0;i<n;i++){
        scanf(" %[^\n]",a[i]);
    }
    for(i=0;i<n;i++){
        printf("%s\n",a[i]);
    }
}

以下是我的输入
4
1112
1912
1892
第1234章

我的异常输出应该如下所示
1112
1912
1892
第1234章

我得到的输出如下
1112191218921234
191218921234
18921234
第1234章

谁能解释我的代码有什么问题?任何帮助,将不胜感激!谢谢:)

【问题讨论】:

  • 提示:长度为4的数组不能容纳长度为4的字符串,nul-terminator的空间不存在。
  • 另外,当使用数组作为字符串时要小心,它们需要空终止才能工作。
  • scanf(" %[^\n]",a[i]);gets() 差。

标签: c arrays string multidimensional-array


【解决方案1】:

你需要改变:

char a[n][n];

进入:

char a[n][n + 1];

对于空终止符。没有它,char 数组将不会被终止并继续打印。

之后你会得到正确的输出:

$ gcc -o prog prog.c; ./prog
4
1112
1912
1892
1234

【讨论】:

  • 外尺寸可以很好的保持为n
  • @RohanBari,然后最好删除这些 cmets。我的已经删除了。
猜你喜欢
  • 2020-04-13
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2023-01-17
  • 2017-04-23
  • 2013-01-10
相关资源
最近更新 更多