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)
- Load each of the ranges and the text "FIRST", "SECOND", etc. from the file inp.txt, into an array, or several arrays, or similar. As I said in the comment above,
fscanf
might 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 give fscanf
a 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)
- Prompt the user to enter a number.
- Look through the array(s) to work out which range the number fits into, and therefore which text to output
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 fopen
function, something like this (declare a pointer FILE* input_file
):
input_file = fopen("c:\\test\\inp.txt", "r") /* "r" opens inp.txt for reading */
Then, it's good to check that the file was successfully opened, by checking if input_file == NULL
.
Then use fscanf
to read details from one line of the file. Loop through the lines of the file until you've read the whole thing. You give fscanf
pointers to the variables you want it to put the information from each line of the file into. (It's a bit like a printf
formatting specifier in reverse).
So, you could declare int range_start, range_end
, and char 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).
while (!feof(input_file)) { /* check for end-of-file */
if(fscanf(input_file, "%d;%d;%s", &range_start, &range_end, range_name) != 3) {
break; /* Something weird happened on this line, so let's give up */
else {
printf("I got the following numbers: %d, %d, %s\n", range_start, range_end, range_name);
}
}
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 fgets
to 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 then sscanf
to read from the string into your integer variables. I haven't tried this way though.