繁体   English   中英

如何存储然后打印2d字符/字符串数组?

[英]how to store and then print a 2d character/string array?

假设我有:老虎,狮子,长颈鹿。

我怎样才能将其存储在一个二维char使用数组for循环和scanf ,然后用打印字一个一个for循环?

就像是

for(i=0;i<W;i++)
{
    scanf("%s",str[i][0]);  //to input the string
}

PS很抱歉提出这样一个基本问题,但我在Google上找不到合适的答案。

首先,您需要创建一个字符串数组。

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];

然后,您需要将字符串输入数组

int i;
for (i=0; i<NUMBER_OF_WORDS; i++) {
    scanf ("%s" , arrayOfWords[i]);
}

最后在oreder打印它们使用

for (i=0; i<NUMBER_OF_WORDS; i++) {
    printf ("%s" , arrayOfWords[i]);
}
char * str[NumberOfWords];

str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte;
memcpy(str[0], "myliteral\0");
//Initialize more;

for(int i = 0; i < NumberOfWords; i++){
    scanf("%s", str[i]);
 } 

你可以这样做。

1)创建一个字符指针数组。

2)动态分配内存。

3)通过scanf获取数据。 下面是一个简单的实现

#include<stdio.h>
#include<malloc.h>

int main()
{
    char *str[3];
    int i;
    int num;
    for(i=0;i<3;i++)
    {
       printf("\n No of charecters in the word : ");
       scanf("%d",&num);
       str[i]=(char *)malloc((num+1)*sizeof(char));
       scanf("%s",str[i]);
    }
    for(i=0;i<3;i++)  //to print the same 
    {
      printf("\n %s",str[i]);    
    }
}
#include<stdio.h>
int main()
{
  char str[6][10] ;
  int  i , j ;
  for(i = 0 ; i < 6 ; i++)
  {
    // Given the str length should be less than 10
    // to also store the null terminator
    scanf("%s",str[i]) ;
  }
  printf("\n") ;
  for(i = 0 ; i < 6 ; i++)
  {
    printf("%s",str[i]) ;
    printf("\n") ;
  }
  return 0 ;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM