How to save and then print the 2nd array of characters / lines?

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

How to save it in a two-dimensional char array using a for and scanf loop and then print the words one by one using a for loop?

Sort of

 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 did not find a suitable answer on Google.

+4
source share
4 answers

First you need to create an array of strings.

 char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD]; 

Then you need to enter a string into an array

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

Finally, in orerer for printing use

 for (i=0; i<NUMBER_OF_WORDS; i++) { printf ("%s" , arrayOfWords[i]); } 
+8
source
 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]); } 
+2
source

You can do it.

1) Create an array of character pointers.

2) Dynamically allocate memory.

3) Get data through scanf. Simple implementation 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]); } } 
+2
source
 #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 ; } 
+1
source

Source: https://habr.com/ru/post/1495559/


All Articles