[英]Parsing a text file in C
我正在制作一个程序,使用文件从周期表中显示您选择的元素。 我尝试将字符串与文件的一行进行比较,但是它不起作用。 如何解决比较问题?
#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;
}
将来,您可能希望包括输入文件,以防万一这是问题的一部分。
假定不会造成任何问题, strncmp()
是解决之道。 格式为strncmp(str1, str2, n)
,其中n
是您要比较的字符数。
您正在使用getline()
存储'\\n'
,这就是为什么strcmp()
返回非零值的原因。 因为scanf()
不包含'\\n'
。
尝试
size_t length = sizeof(name_element);
getline(&name_element, &length, stdin);
他们应该比较平等,但这不能解决问题。
您需要从文件读取的行中删除尾随的'\\n'
,因为最后一行可能不包含'\\n'
或者使用此解决方案也很好,因为如果您使用"%n"
scanf()
说明符。
另外,如果您希望代码更健壮,请检查scanf()
的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.