-1

I wrote this program where the user enter a string n times according to his wish, but I am struggling to print all of the strings that have been read. As it stands, the program just prints the last entered string.

    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int n, count=0;
        char string[10];
        printf("Enter the value of n\n");
        scanf("%d", &n);
        //printf("Enter the words\n");
        while(count<n)
        {
            scanf("%s", string);
            count++;
        }
        printf("The strings that you entered are\n");
        *// I want to print all the strings that I took as input from scanf*
     }
  • This isn't how Stack Overflow works. Read [ask]. – Robert Harvey Jul 18 '21 at 12:40
  • 1
    Please choose titles that explain your issue and that would be useful for other people with the same problem. – user438383 Jul 18 '21 at 12:41
  • 1
    The problem you have is that you have misunderstood what is happening with the array `char string[100]` . The fact that you have called the array `string` is completely irrelevant to solving the problem. All you have is a single array (container) for 100 characters and each time you read a string from scanf, the string fills up the array, one character at a time. You should read about 2-dimensional arrays (an array of arrays). You will then read each new string into separate rows of the array. – CrimsonDark Jul 18 '21 at 12:49

1 Answers1

0
#include <stdio.h>
#include <stdlib.h>
int main() {
  int n;
  int count;
  int i;

  // Create an array of character arrays. Each row of the 2D array
  //will store a sequence of characters (i.e., a string)
  char string[50][100]; //  Can store up to 50 strings of 99 characters
  printf("Enter the value of n\n");
  scanf("%d",&n);
  if(n > 50) {
    fprintf(stderr, "Error. I can't store that many strings\n");
    exit(-1);
  }
  //printf("Enter the words\n");

  // Initialize count here.
  count = 0;
  while(count<n)  {
    // Only the first dimension of the array is referenced in the
    // next statement. scanf fills up the referenced row with the
    // string that's read in
    scanf("%s", string[count]);
    count++;
  }
  printf("The strings that you entered are\n");
  //I want to print all the strings that i took as input from scanf
  for(i = 0; i< n; i++) {
    printf("Word #%02d is : %s\n", i, string[i]);
  }
 }

You might also consider carefully studying this earlier code, taking note, and reading about, malloc, fgets, and the steps that were used to prevent a buffer overflow.

CrimsonDark
  • 661
  • 9
  • 20