-2

I understand how to read in a text file and scan/print the entire file, but how can a line be split into several strings? Also, can variables be assigned to those strings to be called later? My code so far:

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

int main()
{
    FILE *fPointer;
    fPointer = fopen("p1customer.txt", "r");
    char singleLine[150];
    int id;


    while (!feof(fPointer)){
        fscanf(fPointer, "%d", &id);
        printf("%d",id);

    }

    fclose(fPointer);
    return 0;   
}

Example Text File to be read: 99999 John Doe Basketball

Example Output: John Doe has ID number 99999 and plays Basketball

I am attempting to split/tokenize those strings and assign them variables (IDnumber, Name, Sport) and print the output in a new file.

shibaking
  • 61
  • 1
  • 6
  • 1
    Out of curiosity, what does your data look like? Is it all integers as your `fscanf` suggests? – Taelsin Sep 13 '17 at 18:40
  • 4
    You could read string from file using `fgets` (insted of using `feof` use return of `fgets` in loop condition) and then use [`sscanf`](http://www.cplusplus.com/reference/cstdio/sscanf/). – ameyCU Sep 13 '17 at 18:41
  • Essentially, I'm trying to read a line of text consisting of a set of integers and two separate sets of characters and rearrange them in a new file. So I thought there might be a way to actually split/parse each string, assign them to a variable, and rearrange them. – shibaking Sep 13 '17 at 18:43
  • 6
    Read about why [`while (!feof(fp)) {}` is always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). An example of input and expected output would be helpful. – ad absurdum Sep 13 '17 at 18:48
  • 1
    Note that, if end-of-file is reached with the call to `fscanf()`, the `printf()` is executed anyway. And the return value from the call to `fscanf()` is not checked; if input is not as expected, there is no code to handle the problem. – ad absurdum Sep 13 '17 at 18:52
  • 2
    Please post (by editing the question) an example input file of a few lines, and the desired output for each line. I see you don't use `char singleLine[150];` so your intentions are unclear. Did you want code written for you? – Weather Vane Sep 13 '17 at 19:05
  • 2
    "I understand how to read in a text file and scan/print the entire file" and `while (!feof(fPointer)){ fscanf(fPointer, "%d", &id); ...` leaves doubts given that code is not testing the return value of `fscanf()`. Better to use `while (fgets(buf, sizeof buf, fPointer)) { user_code_to_process_string_into_tokens(buf); }` – chux - Reinstate Monica Sep 13 '17 at 19:33
  • Chux I think this is helping in the right direction. Can fgets be followed by fputs to rearrrange newly assigned striings? – shibaking Sep 14 '17 at 00:16

2 Answers2

0

you can use a library function strtok(str,chrs) function. A sequence of calls of strtok(str,chrs) splits str into tokens, each delimited by a character from chrs.

The first call in a sequence is a non Null str.It finds the first token in str consisting of chars not int chrs;it terminates that by overwrtting the next characters of str by \0 and return pointer to token. Each subsequent call,indicated by a NULL value of str,retuens a pointer to next such token, searching from just past the end of privious one.

krpra
  • 466
  • 1
  • 4
  • 19
0

You should post an example of the input file so that you can help in more detail. I've seen you've also entered a string, I guess you want to fill in with something but you did not specify that. If you wanted to treat the file as a list of numbers, the sample of the code might be the following.

#include <stdio.h>

int main() {
    FILE *infile;
    char buf[100];
    int len_file=0;

    if(!(infile = fopen("p1customer.txt", "r"))) { /*checks the correct opening of the file*/
        printf("Error in open p1customer.txt\n");
        return 1;
    }

    while(fgets(buf,sizeof(buf),infile)!=NULL) /*check the lenght of the file (number of row) */
        len_file++;

    int id[len_file];
    int i=0;

    rewind(infile);

    while(fgets(buf,sizeof(buf),infile)!=NULL) {
        sscanf(buf,"%i",&id[i]);
        i++;
    }

    for(i=0;i<len_file;i++)
        printf("%i\n",id[i]);

    fclose(infile);

    return 0;
}

If you want to treat the file as an indefinite list of numbers on each row separated by a space, you can use the parsing of the string by using in the sscanf formatting %31[^ ]which has the task of reading the number until it encounters a space, also you can add a variable that is incremented for each char/number read. Then you can refine the code by checking if there are any characters in the line using the isalpha function in the ctype.h library to see if there are any characters and then insert them into a string until you find the termination character '\ 0'.

The possibilities are infinite so it would useful have the input file, when you provided it, i'll update the answer.

Fabio
  • 336
  • 3
  • 17