Search code examples
cstringiostrtokstrlen

string.h output words C


I need to compare the first and the last letter in a word; if these letters are the same, I need to output that word to a file. But I take words from another file. My problem is i can't guess how i should output all words because in my code, it outputs only the first word. So i understand that i have no transition to others.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include<malloc.h>
#include <string.h>

int main()
{
    char my_string[256];
    char* ptr;

    FILE *f;
    if ((f = fopen("test.txt", "r"))==NULL) {
        printf("Cannot open  test file.\n");
        exit(1);
    }

    FILE *out;
    if((out=fopen("result.txt","w"))==NULL){
        printf("ERROR\n");
        exit(1);
    }

    fgets (my_string,256,f);
    int i;
    int count = 1;

    printf("My string is %d symbols\n", strlen(my_string));

    for (ptr = strtok(my_string," "); ptr != NULL; ptr= strtok(NULL," "))
    {
        int last = strlen(ptr) - 1;
        if ((last != -1) && (ptr[0] == ptr[last]))
        {
            printf("%s\n",ptr);
        }
    }

    printf("\n%s\n",my_string);
    fprintf(out,"%s\n",my_string);
    system("pause");
    fclose(f);
    fclose(out);

    return 0;
}

In my first file there are words:

high day aya aya eye that

From my words from the first file, it outputs only the first word

high

to the second file. I expect the following:

high aya aya eye

Solution

  • You're not outputting anything to the file except at the very end when you fprintf the entire string:

    fprintf(out,"%s\n",my_string);
    

    You need to change printf("%s\n",ptr); to fprintf(out,"%s\n",ptr); in that for loop. Otherwise it will just output everything to the console.