【问题标题】:Loop does not recognize string of char in C循环无法识别 C 中的 char 字符串
【发布时间】:2013-04-29 13:59:28
【问题描述】:

我正在编写代码,我需要使用循环。我正在从如下所示的文件 (data.txt) 中读取数据:

IMPORT 450

EXPORT 200

IMPORT 100

等等。

这是我遇到问题的代码段

inputfile = fopen("c:\\class\\data.txt","r");
fscanf(inputfile,"%s %f", &transaction, &amount);

do{                 
     total += amount;             
     printf("Data %s  %f   %f\n", transaction, amount, total);
     fscanf(inputfile, "%s", &transaction);

}while (transaction == "IMPORT" || transaction == "EXPORT");

当我添加一个 printf 行来检查它显示的是什么“事务”时,它会显示 IMPORT,所以我不确定为什么 do-while 循环没有重复。

谢谢!

【问题讨论】:

    标签: c loops char


    【解决方案1】:

    大概是这样的

        while(2==fscanf(inputfile,"%s %f", transaction, &amount)){
            if(strcmp("IMPORT", transaction)==0)
                total += amount;
            else if(strcmp("EXPORT", transaction)==0)
                total -= amount;
            else
                break;
            printf("Data %s  %f   %f\n", transaction, amount, total);
        }
    

    【讨论】:

      【解决方案2】:

      当您尝试检查事务 == "IMPORT" C 仅比较第一个字符的指针。这确实很好用。也许试试这个代码:

      int str_equal(char* str1, char* str2)
      {
          int i, len;
      
          if ((len = strlen(str1)) != strlen(str2))
          {
              return 0;
          }
      
          for (i = 0; i < len; i++)
          {
              if (toupper(str1[i]) != toupper(str2[i]))
          {
                  return 0;
              }
          }
      
          return 1;
      }
      

      【讨论】:

        【解决方案3】:

        transaction 是什么类型?

        为了将它与fscanf%s 运算符一起使用,它可能是char[],在这种情况下您需要使用strcmp== 运算符将比较字符指针地址,而不是内容。

        【讨论】:

          【解决方案4】:

          假设transaction是一个char数组,比较

          transaction == "IMPORT"
          

          transaction 的地址与字符串文字"IMPORT" 的地址进行比较。

          你需要使用

          while (strcmp(transaction, "IMPORT") == 0 ||
                 strcmp(transaction, "EXPORT") == 0)
          

          比较 C 中的字符串。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-04-15
            • 2014-12-02
            • 2014-03-24
            • 1970-01-01
            • 2017-05-07
            • 2015-10-03
            • 2013-02-17
            • 2018-05-10
            相关资源
            最近更新 更多