【问题标题】:Find string in text file in C在C中的文本文件中查找字符串
【发布时间】:2013-04-18 12:02:30
【问题描述】:

我正在尝试使用 C 在文本文件中搜索始终位于特定位置的字符串。具体来说,我正在寻找三个连续的破折号。当它找到三个破折号时,它应该返回找到它的行。然后它应该继续到下一行并继续搜索三个连续的破折号,直到它到达文件的末尾。每次都是应该打印行号。

这是我目前所拥有的:

int main() {
FILE *f;
char inName[80];
printf("Read text from: ");
scanf(" %79[^\n]s\n", inName);

f  = fopen(inName, "r");
if (f == 0) printf("ERROR: Cannot open file %s for reading.\n", inName);
int lineNumber = 0;

for(;;) {       
    char line[127]; 
    fgets(line, 127, f);
    if (!feof(f)) { 
        lineNumber++;
    } else {
        break;
    }

    double lf;  
    int d, d1;
    char s[30];
    char s1[4];

    sscanf(line, " %d, %s, %s, %s, %s, %d, %d, %lf",
                   &d, &s, &s, &s, &s, &d, &s1, &lf);
    if (s1 == "---") {
        printf("%d\n", lineNumber); // what line 
    }
}
fclose(f);

return(0);
}

此代码运行但不打印任何内容。谁能展示如何完成这项工作?谢谢:)

【问题讨论】:

  • 你试过调试器吗?

标签: c string file


【解决方案1】:

这不是 C 中比较字符串的方法:

if (s1 == "---")

s1 的地址与字符串文字"---" 的地址进行比较。 使用strcmp():

if (strcmp(s1, "---") == 0)
{

始终检查sscanf() 的返回值,以确保变量在尝试使用它们之前已实际分配了值。使用"%s" 格式说明符处理时,, 逗号字符不被视为分隔符,仅使用空格作为分隔符。为防止消耗,,请使用扫描集,类似于您在程序前面所做的(注意对sscanf() 参数的更正):

if (sscanf(line,
           " %d, %29[^,], %29[^,], %29[^,], %29[^,], %d, %3[^,], %lf",
             &d, s,       s,       s,       s,       &d, s1,     &lf) == 8)
{
}

【讨论】:

  • 注意 sscanf 格式字符串也有错误; &s1 在应该是 %s 时与 %d 匹配。
  • @NigelHarper,我错过了,ta,我错过了&s
【解决方案2】:

您无法将char[]== 进行比较。请改用strcmp

if( strcmp(s1, "---") == 0 )

【讨论】:

    【解决方案3】:
    if (s1 == "---")
    

    你用错误的方式比较字符串,你应该使用strcmp()

    按照这个例子 http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1057537653&id=1043284385

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多