Search code examples
carraysword-count

Reading words and storing them in 2-D array in C


I am trying to write a program that reads lines word by word and puts each word in an array (later I want to do some operations on those words but this isn't an issue now) and in the output there should be a number of words in each line. For example:

input:
good morning my neighbors!
how are you?

output:
4
3

Here is my code:

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

int main()
{
    char word[100];
    char wordArray[100][100];
    int count = 0;
    for(;scanf("%s", word)!=EOF;)
    {
        strcpy(wordArray[count], word);
        count++;
    }
    printf("%d", count);

    return 0;
}

But it gives me just 7 in the output (number of all words on both lines). If I put printf function inside the for loop then I get 1234567 as an output. How do I make it count words on one line and print it then set the count to zero and start over on the next line?


Solution

  • You should use fgets or getline because scanf reads word by word not all words in one line.

    The code:

    #include <stdio.h>
    #include <string.h>
    #define SIZE 100
    
    int main()
    {
        char wordArray[SIZE][SIZE];
        int count[SIZE];
        int c = 0;
        while(fgets( wordArray[c], SIZE, stdin) && c < SIZE)
        { 
            for(int i = 0; wordArray[c][i] != '\0' ; i++) {
                // remove enter character at the end of each line, not necessary in this case but mabe later when you work with all works
                wordArray[c][strcspn ( wordArray[c], "\n" )] = '\0'; 
                if (wordArray[c][i] == ' ') {
                     count[c]++; // increase the number of words if we meet space character
                }
            }
            c++;
        }
        for (int i = 0; i < c; i++) //print all the counts
            printf("%d", count[i] + 1);
    
        return 0;
    }