adding words to char array

I have a sentence stored in char text[100] . I have to rearrange the words like this : one word per line and the words that have at least n letters have priority.

I thought about storing the words into 2d char arrays depending on how many letters the word has, but I can't figure how to add and keep the words into the array. I tried with strcpy() but in the end all I'm left with is the last valid word.
1
2
char big[100][25] //for words >= n letters
char small[100][n] //for words <=n-1 letters 
Using the C library function strtok on your C string will split your string into one word chunks you can then store in whatever arrangement you want.

http://www.cplusplus.com/reference/cstring/strtok/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    
int main()
{ unsigned int n,i=0,j=0;

  bool ok=false,ok2=false;
  
  unsigned int big_word=0,small_word=0;
  
  char text[101],small[100][10],big[100][30];
  
  cin.get(text,101);
  cin>>n;
  char*word=strtok(text," ");

  while(word!=NULL)
   {
       if(strlen(word)>=n)
          {  strcpy(big[i++],word);
              big_word++;
              ok=true;
          }
       else
          {strcpy(small[j++],word);
            small_word++;
            ok2=true;
          }


      word=strtok(NULL," ");
   }
   if(!ok|| !ok2)
   {
       cout<<"nu exista";
       return 0;
   }

    for(i=0;i<=big_word;i++)
      cout<<big[i]<<endl;

    for(j=0;j<=small_word;j++)
      cout<<small[j]<<endl;
    return 0;
}



I'm very close to getting the result I wanted but I really don't know what's wrong.
What results are you expecting? What results are you actually getting?

We can't read your mind, our crystal balls are busted. You have to tell us what is wrong so we can help guide you.
Sorry about that. I figured it though.
Here is an example: n=4.
"My grandma is very old" should print
grandma
very
My
is
old

The problem was at lines 37 and 40. It should have been <big_word and <small_word because the first word in the array occupied position 0 in the 2d array yet big_word and small_word started from 1.
Last edited on
Topic archived. No new replies allowed.