How to extract a word from a file?

Comments

  • [b][red]This message was edited by thellman at 2002-8-1 0:55:13[/red][/b][hr]
    [b][red]This message was edited by thellman at 2002-8-1 0:54:50[/red][/b][hr]
    Hi,

    Well it depends. But this is one way (Done C-style).

    [code]

    #include
    #include
    #include

    int main()
    {
    char word[100] = {0};
    FILE* fp;
    char ch;
    int i = 0;
    // Test that the file really opened
    if ( fp = fopen( "test.txt", "r" ) )
    {
    // Take chars from file until char is a space, newline, etc.
    while ( !isspace(ch) )
    {
    ch = fgetc(fp);
    word[i] = ch;
    i++;
    }
    fclose(fp);
    }

    else
    printf( "Error opening file" );

    // Null-terminate the string
    word[strlen(word)] = '';
    printf( "%s", word );
    return 0;
    }

    [/code]

    This of course takes only the first word from the file and doesn't take commas, semicolons, etc. in to consideration. But I think this'll get you started.



    Teemu Hellman
    C++/CORBA specialist@Yomi Applications, Finland
    teemu.hellman@yomi.com





Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion