简体   繁体   中英

Parsing a text file in C

I am making a program that displays the element of your choice from the periodic table using a file. I try to compare a string with a line of the file, but it doesn't work. How can I fix the comparison?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char * line = NULL;
    char name_element[1000];
    size_t len=0;
    ssize_t read;

    FILE*table;
    table=fopen("Data.txt","r");

    printf("Please enter the element you are looking for:\n");
    scanf("%s",name_element);

    while ((read = getline(&line, &len, table))!=-1){
        i=strcmp(name_element,line);
        if  (strcmp(line,name_element)==0) {
            while ((read = getline(&line, &len, table))!=-1) {
                if(strcmp(line,"////")!=0) {
                    printf("%s", line);
                } else {
                    break;
                }
            }
        }
    }    
    fclose(table);
    return 0;
}

In the future, you may want to include the input file, just in case that is part of the problem.

Assuming that won't cause any problems, strncmp() is the way to go. The format is strncmp(str1, str2, n) where n is the number of characters you want to compare.

You are using getline() which stores the '\\n' that's why strcmp() is returning a non-zero value. Because scanf() doesn't include the '\\n' .

Try

size_t length = sizeof(name_element);
getline(&name_element, &length, stdin);

and they should compare equal, but that will not solve the problem.

You need to remove the trailing '\\n' from the line read from the file, because the last line might not contain the '\\n' or use this solution which is also good because you may know the string length if you use the "%n" scanf() specifier.

Also, please check the return value from scanf() if you want your code to be robust.

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