Mustafa
Mustafa

Reputation: 1

How to scan in strings using a loop then storing those words in an array?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main () 
{
 char word[100][21] ;

puts( "Enter Your Words" );

puts( "Enter STOP To Get Your Results" );

   while( strcmp( word, "STOP" ) ) 

   {
    scanf( "%20s", word );

   }

return 0;
}

After I scan in a word id like to store it into an array called storing[][], but I dont know how to achieve that, and also I dont want to store the terminating STOP word

Upvotes: 0

Views: 220

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Code what you want.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define WORD_MAX 100

int main (void)
{
    char storing[WORD_MAX][21]; /* you want the words stored into storing[][], not word */
    char buffer[21]; /* a buffer to store the word temporaly for not to store STOP to storing */
    int wordCount = 0; /* count how many words are stored */

    puts( "Enter Your Words" );

    puts( "Enter STOP To Get Your Results" );

    /* loop while there is room to store new word left in the array,
     * successfully read something and what is read is not the STOP word */
    while(wordCount < WORD_MAX && scanf("%20s", buffer) == 1 && strcmp(buffer, "STOP") != 0)
    {
        /* store the word read and increment the count */
        strcpy(storing[wordCount++], buffer);
    }

    /* sample code for testing: print what is read */
    {
        int i;
        for (i = 0; i < wordCount; i++) printf("%03d : %s\n", i, storing[i]);
    }

    return 0;
}

Upvotes: 1

Related Questions