如何在c中解析操作?

如何在c中解析操作?,c,C,我决定通过编写一个简单的小程序来刷新我的C语言。我试图从文件“myfile.txt”中读取,应用操作并打印到标准输出。该文件包含一行: 2 + 3 我期望的结果是: 5 但我发现这比我最初预期的要复杂得多。起初,我尝试使用getc()但一直得到segfaults,然后我尝试使用fscanf()。除了打印以下内容的print语句外,添加到stdin没有任何输出: 2 1556274040 为什么输出为2 1556274040?还有没有更好的方法来尝试应用从文件读取的操作,比如我可以使用的

我决定通过编写一个简单的小程序来刷新我的C语言。我试图从文件“myfile.txt”中读取,应用操作并打印到标准输出。该文件包含一行:

2 + 3
我期望的结果是:

5
但我发现这比我最初预期的要复杂得多。起初,我尝试使用getc()但一直得到segfaults,然后我尝试使用fscanf()。除了打印以下内容的print语句外,添加到stdin没有任何输出:

2   1556274040
为什么输出为2 1556274040?还有没有更好的方法来尝试应用从文件读取的操作,比如我可以使用的apply()函数? 这是我的密码:

int main()
{
  int ans, num1, num2;
  char oper;
  FILE *pFile;
  pFile = fopen("myfile.txt", "r");
  if (pFile != NULL) {
    fscanf(pFile, "%d", &num1);
    fscanf(pFile, "%c", &oper);
    fscanf(pFile, "%d", &num2);
    printf ("%d %c %d", num1, oper, num2);
    if (oper == '+') {
      ans = num1 + num2;
      printf(ans);
    }
    fclose(pFile);
  }
  return 0;
}
打印
int变量
的语法无效。 试试这个-

printf("%d\n",ans);
照你说的
您可以使用而不是使用
fscanf
来读取文件内容,但请确保检查其返回。

这里有一个可能的解决方案

#include <stdio.h>    

int main() {    
  int ans, num1, num2;    
  char oper;    
  FILE *pFile;

  pFile = fopen("myfile.txt", "r"); // might need to specify binary/text

   if (pFile != NULL) {
     // fscanf(pFile, "%d", &num1); need spaces in format specifier.
     // fscanf(pFile, "%c", &oper);
     // fscanf(pFile, "%d", &num2);
     // one way to solve...

     fscanf(pFile, "%d %c %d", &num1, &oper, &num2);

     fclose(pFile); // stopping some errors
     printf ("%d %c %d = ", num1, oper, num2);
   } // end if
   else    
     puts("fopen returned NULL");

   if (oper == '+') {
     ans = num1 + num2;
     printf("%d",ans);
   } // end if

    return 0;
}  // end main
#包括
int main(){
int ans,num1,num2;
字符操作器;
文件*pFile;
pFile=fopen(“myfile.txt”,“r”);//可能需要指定二进制/文本
if(pFile!=NULL){
//fscanf(pFile、%d、&num1);格式说明符中需要空格。
//fscanf(pFile、%c、&oper);
//fscanf(pFile、%d、&num2);
//解决问题的一种方法。。。
fscanf(pFile、%d%c%d、&num1、&oper、&num2);
fclose(pFile);//停止某些错误
printf(“%d%c%d=”,num1,oper,num2);
}//如果结束,则结束
其他的
看跌期权(“fopen返回空”);
如果(操作=='+'){
ans=num1+num2;
printf(“%d”,ans);
}//如果结束,则结束
返回0;
}//末端总管

您需要在
fscanf
格式字符串中允许空白。
fscanf(pFile、%c、&oper)注意前导空格。这允许在字符(在本例中是运算符)前面有任意数量的空白字符。一个真正有趣的练习是解析
中缀
符号。它将允许您将像
1+2*3-4*5这样的表达式转换为一棵树,并正确计算其值。最好添加一个
\n
@Jite刚刚这样做。
#include <stdio.h>    

int main() {    
  int ans, num1, num2;    
  char oper;    
  FILE *pFile;

  pFile = fopen("myfile.txt", "r"); // might need to specify binary/text

   if (pFile != NULL) {
     // fscanf(pFile, "%d", &num1); need spaces in format specifier.
     // fscanf(pFile, "%c", &oper);
     // fscanf(pFile, "%d", &num2);
     // one way to solve...

     fscanf(pFile, "%d %c %d", &num1, &oper, &num2);

     fclose(pFile); // stopping some errors
     printf ("%d %c %d = ", num1, oper, num2);
   } // end if
   else    
     puts("fopen returned NULL");

   if (oper == '+') {
     ans = num1 + num2;
     printf("%d",ans);
   } // end if

    return 0;
}  // end main