Reading words from a file using fscanf

I have a .txt file with the following encoding:

Alpha-Beta-Gamma-Delta-Epsilon
Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi
Ni-Ksi-Pi-Ro-Sigma

      

I want to read these words and store them in an array. I read these words withfscanf(fp, "%[^-]", word)

But when I put fscanf

inside, it keeps reading the same word. If I put it inside a while statement, it won't repeat itself.

The goal is to read each word separately from Alpha to Sigma

I provide you with a minimal-testable code with the problem:

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

int main(){
    FILE *fp;
    char *word = (char*)malloc(40);
    int count = 0;
    char* Words[30]; //max 30
    fp = fopen("MyWords.txt","r"); //read only
    int r = 1;
    while(1){
        if(fscanf(fp, "%[^-]", word) == EOF) break;
        printf("%s",word);
    }
    fclose(fp);
    return 0;
}

      

Note. I don't want to modify the file. Also how do I handle the \n

characheter

+3


source to share


2 answers


An input limit with a width specifier of 39, 1 is less than the 40 bytes available for word

as fscanf()

will add a null character. Continue reading until successful completion of return fscanf()

1. Use the following separator: '-'

or '\n'

,

while(fscanf(fp, "%39[^-\n]", word) == 1) {
    printf("<%s>\n",word);
    fscanf(fp, "%*[-\n]"); // consume delimiter, no need to save.
}

      



Note. Use [^-\n]

, not [^\n-]

, as placement -

later looks like the start of an incomplete scan range.

+4


source


The above answer works really well. If you don't want regex complications in your code, even if they are simple, use strtok

after reading the entire line. Then add it to the array.

while(1){
    if(fscanf(fp, "%s", word) == EOF) break;
    printf("%s\n",word);
    const char s[2] = "-";
    char *token;
    token = strtok(word, s);
    while( token != NULL ) 
    {
        printf("%s\n", token );
        token = strtok(NULL, s);
    }
}

      

What gives the conclusion



Alpha-Beta-Gamma-Delta-Epsilon

Alpha
Beta
Gamma
Delta
Epsilon

Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi

Zeta
Eta
Theta
Iota
Kappa
Lamda
Mi

Ni-Ksi-Pi-Ro-Sigma

Ni
Ksi
Pi
Ro
Sigma

      

Hooray!

+1


source







All Articles