How to print looping sting? [C language] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to print looping sting? [C language]

Example (my code): #include<stdio.h> int main(){ char word[100]; int n; scanf("%d", &n); for(int i=1; i<=n; i++){ printf("word %d = ", i) scanf ("%s", word); } for(int i=1; i<=n; i++){ printf("word %d = ", i) printf ("%s", word); } return 0; } Example, when i put 3 case, word 1 = car, word 2 = bike, word 3 = car, why the output is word 1 = car, word 2 = car, word 3 = car?

9th Nov 2020, 1:16 PM
Briana
Briana - avatar
5 Answers
+ 1
Briana every time you read a word you save it overwriting the previous. You have only one array of characters. You can save all the three words there by using: fgets( word, 100, stdin ); And then you need strtok() to extrapolate the words from the array of characters. Or you can use a 2D array of characters char word[N][L]; wher N is the maximum number of words and L the maximum length of each word and then you can: scanf("%s", word[i]); or you can use an array of strings char *word[N]; but then you need to allocate memory for each string using malloc()
9th Nov 2020, 2:20 PM
Davide
Davide - avatar
0
What are the exact inputs and what output you expect?
9th Nov 2020, 1:49 PM
Abhay
Abhay - avatar
0
Abhay Input : car bike car Output : word 1 = car word 2 = bike word 3 = car that's my expect
9th Nov 2020, 1:51 PM
Briana
Briana - avatar
0
Then simply add printf("%s\n",word); to the first for loop and remove the second for loop as well
9th Nov 2020, 1:53 PM
Abhay
Abhay - avatar
0
Abhay can we put in different place? (Not in one loop)
9th Nov 2020, 2:02 PM
Briana
Briana - avatar