-1

Hi I'm completely new to C and used to code in python so this has been bothering me for a while but I couldn't find an answer that I've been looking for so I decided to ask here.

I am reading a file called "input_date.txt" and will have to split it with delimiter / and store each part into different int variable. Here's what I have so far:

int mm, dd, yy;

FILE* fp = fopen("input_date.txt", "r");

In the input_date.txt file there is only one line

5/17/07

I'll have to split them and store 5 in mm, 17 in dd and 07 in yy (all int variables). I kinda figured that I can use strsep but I'm still not too sure how to work with it (I barely started learning C) so any help would be appreciated.

IrAM
  • 1,720
  • 5
  • 18
yerim2
  • 83
  • 10
  • `strsep` really is a useful tool, here's a good link with an example https://c-for-dummies.com/blog/?p=1769 . Apart from that, you can also use `strtok`: https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/ – mediocrevegetable1 Feb 06 '21 at 07:42
  • Research `fscanf`, `fgets`, `sscanf` and `strtok`. – jwdonahue Feb 06 '21 at 07:43
  • @mediocrevegetable1, `strsep` is not part of the C standard library. – jwdonahue Feb 06 '21 at 07:45
  • @jwdonahue I am aware, but I assumed @yerim2 can use `strsep` since they mentioned it in their post. – mediocrevegetable1 Feb 06 '21 at 07:47
  • 1
    @mediocrevegetable1, beginners present us with lots of [XY problems](https://en.wikipedia.org/wiki/XY_problem). We should steer them towards the standards based solutions until they have achieved a minimum level of competence. – jwdonahue Feb 06 '21 at 07:51
  • Does this answer your question? [Split string with delimiters in C](https://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c) – jwdonahue Feb 06 '21 at 07:53
  • @jwdonahue thanks for the advice, I'll keep that in mind in the future. – mediocrevegetable1 Feb 06 '21 at 07:54

1 Answers1

1

fscanf might do what you want?

if (fscanf(fp, "%d/%d/%d",&mm,&dd,&yy) != 3) {
    /* Handle error */
    fputs ("error: invalid date format.\n", stderr);            
}
Tony
  • 1,645
  • 1
  • 10
  • 13
  • `fscanf` returns the number of successfully matched and assigned inputs. A non-zero return is not an error. – jwdonahue Feb 06 '21 at 07:48
  • @jwdonahue. Thanks, changed it to 3. It throws an error if all three items were not assigned. – Tony Feb 06 '21 at 07:51
  • 1
    Personally, I'd prefer seeing `fgets()` followed by `sscanf()`, but you get the nod for showing how to correctly ***check the return*** `:)` You may also want to show `/* handle error */` and the `printf()` is better `fputs ("error: invalid date format.\n", stderr);` so it is written to `stderr` and since there are no conversions involved, `printf()` can simply be replaced with `fputs()` – David C. Rankin Feb 06 '21 at 08:54
  • @DavidC.Rankin Good suggestion. I have changed the error handling accordingly. – Tony Feb 06 '21 at 10:04