简体   繁体   English

用C解析文本文件

[英]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. 假定不会造成任何问题, strncmp()是解决之道。 The format is strncmp(str1, str2, n) where n is the number of characters you want to compare. 格式为strncmp(str1, str2, n) ,其中n是您要比较的字符数。

You are using getline() which stores the '\\n' that's why strcmp() is returning a non-zero value. 您正在使用getline()存储'\\n' ,这就是为什么strcmp()返回非零值的原因。 Because scanf() doesn't include the '\\n' . 因为scanf()不包含'\\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. 您需要从文件读取的行中删除尾随的'\\n' ,因为最后一行可能不包含'\\n'或者使用此解决方案也很好,因为如果您使用"%n" scanf()说明符。

Also, please check the return value from scanf() if you want your code to be robust. 另外,如果您希望代码更健壮,请检查scanf()的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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