Search code examples
carraysmaxletter

how can i insert no more than 5 sentences and no more than 50 letters per each sentence in C


before each sentence it needs to say the number of the sentence im writing. starting the count from one. what i mean is:

How many sentences you want to enter [1-5]? 
2
sentence 1: write what you want
sentence 2: here as long as its less then 50 letters

my problem is that i dont know how to limit the number of letters, without needing to insert them all. if i write

 for(i=0; i<50; i++)

i will need to enter all the 50 letters, but if i want i need to be able to write even only 1. so that is what i have done so far: (note that i dont need to ask the user how many letters he wants to enter)

char text[5][50]={0};
int x=0, i=0, n=0, m=0;

   printf("How many sentences you want to enter [1-5]?\n");
   scanf("%d", &n);
   printf("how many letters [1-50]?\n");
   scanf("%d", &m);

   for (x=1; x<=n; x++)// will print max of 5 sentences
   {
       printf("Sentence %d: \n", x);
        for(i=0; i<m; i++)// will print max of 50 letters
        {
            scanf(" %c", &text[x][i]);
        }
   }

thanks a lot for the help!


Solution

  • for(i=0;i<n;i++)
    {
      if(fgets(text,50,stdin) != NULL) /* Read just 50 character */
      {
         // Do your stuff
       }
    }
    

    PS: fgets() comes with a newline character