I am new to C programming, so I am having difficulties with the problem below.
I have a text file inp.txt which contains information like the following:
400;499;FIRST;
500;599;SECOND;
670;679;THIRD;
I need to type a number and my program needs to compare it with numbers from the inp.txt file.
For example, if I type 450, it’s between 400 and 499, so I need write to the word FIRST to the file out.txt
I have no idea how to convert a character array to an int.
I think you’ll want these general steps in your program (but I’ll leave it to you to figure out how you want to do it exactly)
fscanfmight be handy. This page describes how to use it – the page is about C++, but using it in C should be the same http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/. Roughly speaking, the idea is that you givefscanfa format specifier for what you want to extract from a line in a file, and it puts the bits it finds into the variables you specify)Edit: I’ll put some more detail in, as asker requested. This is still a kind of skeleton to give you some ideas.
Use the
fopenfunction, something like this (declare a pointerFILE* input_file):Then, it’s good to check that the file was successfully opened, by checking if
input_file == NULL.Then use
fscanfto read details from one line of the file. Loop through the lines of the file until you’ve read the whole thing. You givefscanfpointers to the variables you want it to put the information from each line of the file into. (It’s a bit like aprintfformatting specifier in reverse).So, you could declare
int range_start, range_end, andchar range_name[20]. (To make things simple, let’s assume that all the words are at most 20 characters long. This might not be a good plan in the long-run though).Hopefully that gives you a few ideas. I’ve tried running this code and it did seem to work. However, worth saying that fscanf has some drawbacks (see e.g. http://mrx.net/c/readfunctions.html), so another approach is to use
fgetsto get each line (the advantage of fgets is that you get to specify a maximum number of characters to read, so there’s no danger of overrunning a string buffer length) and thensscanfto read from the string into your integer variables. I haven’t tried this way though.