4

Suppose I have the words: tiger, lion, giraffe.

How can I store it in a two dimensional char array using for loop and scanf and then print the words one by one using a for loop?

Something like

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

PS Sorry for asking such a basic question, but I couldn't find a suitable answer on Google.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
guitar_geek
  • 498
  • 2
  • 9
  • 19

4 Answers4

8

First you need to create an array of strings.

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];

Then, you need to enter the string into the array

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

Finally in oreder to print them use

for (i=0; i<NUMBER_OF_WORDS; i++) {
    printf ("%s" , arrayOfWords[i]);
}
Ran Eldan
  • 1,350
  • 11
  • 25
2
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]);
 } 
KrisSodroski
  • 2,796
  • 3
  • 24
  • 39
2

You can do this way.

1)Create an array of character pointers.

2)Allocate the memory dynamically.

3)Get the data through scanf. A simple implementation is below

#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]);    
    }
}
Santhosh Pai
  • 2,535
  • 8
  • 28
  • 49
1
#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 ;
}
Mario
  • 35,726
  • 5
  • 62
  • 78
slothfulwave612
  • 1,349
  • 9
  • 22