[英]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.