简体   繁体   中英

Difficulties understanding how to take elements from a file and store them in C

I'm working on an assignment that is supposed to go over the basics of reading a file and storing the information from that file. I'm personally new to C and struggling with the lack of a "String" variable.

The file that the program is supposed to work with contains temperature values, but we are supposed to account for "corrupted data". The assignment states:

Every input item read from the file should be treated as a stream of characters (string), you can use the function atof() to convert a string value into a floating point number (invalid data can be set to a value lower than the lowest minimum to identify it as corrupt)."

The number of elements in the file is undetermined but an example given is:

37.8, 38.a, 139.1, abc.5, 37.9, 38.8, 40.5, 39.0, 36.9, 39.8

After reading the file we're supposed to allow a user to query these individual entries, but as mentioned if the data entry contains a non-numeric value, we are supposed to state that the specific data entry is corrupted.

Overall, I understand how to functionally write a program that can fulfill those requirements. My issue is not knowing what data structure to use and/or how to store the information to be called upon later.

The closest to an actual string datatype which you find in C is a sequence of char s which is terminated by a '\0' value. That is used for most things which you'd expect to do with strings.

Storing them requires just sufficent memory, as offered by a sufficiently large array of char , or as offered by malloc() .

I think the requirements of your assignment would be met by making a char array as buffer, then reading in with fgets() , making sure to not read more than fits into your array and making sure that there is a '\0' at the end.

Then you can use atof() on the content of the array and if it fails do the handling of corrupted input. Though I would prefer sscanf() for its better feedback via separate return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM