Search code examples
cstringgetchar

storing each word in a 2d string C


i want to store each word in a 2d string. The code i wrote is working with no errors the only issue is when there are two spaces or more, it stores the space as a word. If anyone knows how can i fix this

This is my code:

#include <stdio.h>
#include <ctype.h>
#define IN  1
#define OUT 0

int main()
{
    char words[100][1000];
    int i=0, k, j=0, m=0;
    int state = OUT;
    int nw = 0;


    while((k = getchar()) != EOF)
    {
        if((isspace(k)!= 0)|| (ispunct(k)!= 0))
        {
            state = OUT;
            words[i][j] = '\0';
            i++;
            j = 0;
        } 
        else
        {
            words[i][j++]= k;
            if(state == OUT)
            {
                state = IN;
                nw++;
            }
        }
    }
    
    
    return 0;
}

Solution

  • You need to skip all the whitespace before entering a new word by considering the last character. Also you can simplify checking for space and punctuation.

    #include <stdio.h>
    #include <ctype.h>
    #define IN  1
    #define OUT 0
    
    int main()
    {
        char words[100][1000];
        int i=0, k, j=0, m=0;
        int state = OUT;
        int nw = 0;
    
        int last_char = ' ';
        while((k = getchar()) != EOF)
        {
            if((isspace(k)|| ispunct(k)) && !isspace(last_char))
            {
                state = OUT;
                words[i][j] = '\0';
                i++;
                j = 0;
            } 
            else if (!isspace(k))
            {
                words[i][j++]= k;
                if(state == OUT)
                {
                    state = IN;
                    nw++;
                }
            }
            last_char = k;
        }
        
        
        return 0;
    }