简体   繁体   中英

Having trouble comparing strings in file to an array of strings inputted by user in C

I have tried to research this question, but was unable to find anything that would help me. I have been constantly trying to debug using fprint , but I still cannot figure it out.

I am an intermediate programmer, and would love if I could get some help here. Here is my code:

int i = 0;
const int arraySize = 10;
char buf[256];
char str[256];
char buffer[256];
char *beerNames[arraySize] = { };

FILE *names;
FILE *percent;
i = 0;
int numBeers = 0;
printf("Please enter a name or (nothing to stop): ");
gets(buf);
while (strcmp(buf, "") != 0) {
    beerNames[i] = strdup(buf);
    i++;
    numBeers++;

    if (numBeers == arraySize)
        break;

    printf("Please enter a name or (nothing to stop): ");
    gets(buf);
}

// now open files and look for matches of names:        //      
names = fopen("Beer_Names.txt", "r");
percent = fopen("Beer_Percentage.txt", "r");

while (fgets(str, sizeof(str) / sizeof(str[0]), names) != NULL) {
    fgets(buffer, sizeof(buffer) / sizeof(buffer[0]), percent);
    for (i = 0; i < numBeers; i++) {
        if (strcmp(str, beerNames[i]) == 0) {
            printf("Beer: %s Percentage: %s\n", str, beerNames[i]);
            break;
        }
    }
}

fclose(names);
fclose(percent);

So, the issue that I am having is when I try to strcmp() , it is not comparing properly and is returning either a -1 or a 1 . I have tried printing out the strcmp() values as well and it just ends up skipping the match when it equals to 0.

My Beer_Names.txt (shortened) looks like this:

Anchor Porter
Anchor Steam
Anheuser Busch Natural Light 
Anheuser Busch Natural Ice
Aspen Edge
Big Sky I.P.A. 
Big Sky Moose Drool Brown Ale 
Big Sky Powder Hound (seasonal) 
Big Sky Scape Goat Pale Ale 
Big Sky Summer Honey Ale (seasonal) 
Blatz Beer 
Blatz Light
Blue Moon

And my Beer_Percentage.txt (shortened) looks like this:

5.6
4.9
4.2
5.9
4.1
6.2
5.1
6.2
4.7
14.7
4.8
0
5.4

This is not for a homework assignment, I am just doing a personal project and I trying to get better at C.

You're problem is that gets() does not return the newline character as part of the string, while fgets() does.

So when the user entered value "Anchor Porter" is read with gets, your string looks like this "Anchor Porter\\0" , but when you read it from a file with fgets it ends up like this "Anchor Porter\\n\\0" , which will not compare equal.

gets(buf);

I know gets(3) is convenient, and I know this is a toy, but please do not use gets(3) . It is impossible to write secure code with gets(3) and there is a reasonable chance that future C libraries might not even include this function. (Yes, I know it is standardized but we can hope future versions will omit it; POSIX.1-2008 has removed it.) Reasonable compilers will warn you about its use. Use fgets(3) instead.

while (fgets(str, sizeof(str) / sizeof(str[0]), names) != NULL) {

sizeof(char) is defined to be 1 . This is unlikely to change, and you're unlikely to change the type of the array. It's generally not a big deal, but you cannot use a construct like this as often as you might suspect -- you can use it in this case only because str[] was declared in an enclosing scope of this line. If str were passed as a parameter, the sizeof(str) operator would return the size of a data pointer and not the size of the array. Don't get too used to this construct -- it won't always work as you expect.

names = fopen("Beer_Names.txt", "r");
percent = fopen("Beer_Percentage.txt", "r");

while (fgets(str, sizeof(str) / sizeof(str[0]), names) != NULL) {
    fgets(buffer, sizeof(buffer) / sizeof(buffer[0]), percent);

Please take the time to check fopen(3) for success or failure. It's a good habit to get into, and if you provide a good error message, it might save you time in the future, too. Replace the fopen() lines with something like this:

names = fopen("Beer_Names.txt", "r");
percent = fopen("Beer_Percentage.txt", "r");

if (!names) {
    perror("failed to open Beer_Names.txt");
    exit(1);
}
if (!percent) {
    perror("failed to open Beer_Percentage.txt");
    exit(1);
}

You could wrap that up into a function that does fopen() , checks the return value, and either prints the error message and quits or returns the FILE* object.

And now, the bug that brought you here: Robert has pointed out that fgets(3) and gets(3) handle the terminating newline of input differently. (One more reason to get ridd of gets(3) as soon as possible.)

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