reading multiple variable types from single line in file C

后端 未结 5 1204
无人及你
无人及你 2021-01-27 14:09

Alright I\'ve been at this all day and can\'t for the life of me get this down, maybe you chaps can help. I have a file that reads as follows

1301,1055150

5条回答
  •  别那么骄傲
    2021-01-27 14:55

    fscanf reads one line at a time, and you can easily capture the contents of each line because your file is formatted pretty nicely, especially due to the comma separation (really useful if none of your separated values contain a comma).

    You can pass fscanf a format like you're doing with "%d" to capture an int, "%s" to capture a string (ends at white space, be weary of this when for example trying to find a name like "Annitto Grassis, which would require 2 %s's), etc, from the currently read line of the file. You can be more advanced and use regex patterns to define the contents you want captured as chars, such as "Boatswain", a sequence comprised chars from the sets {A-Z}, {a-z}, and the {"}. You'll want to scan the file until you reach the end (signified by EOF in C) so you can do such and capture the contents of the line and appropriately assign the values to variables like so:

    while( fscanf(inputf, "%d,%d,%[\"A-Za-z ],%[\"A-Za-z .]", &term, &id, lastname, firstname) != EOF) {

    .... //do something with term, id, lastname, firstname - put them in a student struct

    }

    For more about regex, Mastering Regex by Jeff Friedl is a good book for learning about the topic.

提交回复
热议问题