Truncating a string while storing it in an array in c

Posted by Nick on Stack Overflow See other posts from Stack Overflow or by Nick
Published on 2013-11-11T21:28:26Z Indexed on 2013/11/11 21:53 UTC
Read the original article Hit count: 197

Filed under:
|
|
|

I am trying to create an array of 20 character strings with a maximum of 17 characters that are obtained from a file named "words.dat". After that the program should truncate the string only showing the first 17 characters and completely ignore the rest of that string. However

My question is: I am not quite sure how to accomplish this, can anyone give me some insight on how to accomplish this task?

Here is my current code as is:

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

    #define WORDS 20
    #define LENGTH 18

    char  function1(char[WORDS][LENGTH]);

int main( void )
{

    char word_array [WORDS] [LENGTH]; 

    function1(word_array);

    return ( 0 ) ;

}

char function1(char word_array[WORDS][LENGTH])
{
    FILE *wordsfile = fopen("words.dat", "r");
    int i = 0;

    if (wordsfile == NULL)
        printf("\nwords.dat was not properly opened.\n");
    else
    {
        for (i = 0; i < WORDS; i++)
        {
            fscanf(wordsfile, "%17s", word_array[i]);
            printf ("%s \n", word_array[i]);
        }
        fclose(wordsfile);
    }
    return (word_array[WORDS][LENGTH]);
}

words.dat file:

Ninja
 DragonsFury
  failninja
   dragonsrage
    leagueoflegendssurfgthyjnu
     white
      black
       red
        green
         yellow
          green
           leagueoflegendssughjkuj
            dragonsfury
             Sword
              sodas
               tiger
                snakes
                 Swords
                  Snakes
                   sage

Sample output:

blahblah@fang:~>a.out
Ninja 
DragonsFury 
failninja 
dragonsrage 
leagueoflegendssu 
rfgthyjnu 
white 
black 
red 
green 
yellow 
green 
leagueoflegendssu 
ghjkuj 
dragonsfury 
Sword 
sodas 
tiger 
snakes 
Swords 
blahblah@fang:~>

What will be accomplished afterwards with this program is:

After function1 works properly I will then create a second function name "function2" that will look throughout the array for matching pairs of words that match "EXACTLY" including case . After I will create a third function that displays the 20 character strings from the words.dat file that I previously created and the matching words.

© Stack Overflow or respective owner

Related posts about c

    Related posts about arrays