带有or-expression的If语句中的语法错误

时间:2022-12-27 20:27:27

In my code for a calculator in c++, I am getting a syntax error involving the argc variable in the following clause:

在我的c ++计算器代码中,我在下面的子句中遇到了一个涉及argc变量的语法错误:

if (argc==4 || argv[3]="s"){
    result=no1 - no2;
    cout<<result<<endl;
    return 0;
} 

whereas the following code with the same structure compiles,

而以下具有相同结构的代码编译,

if ( a || b ){
    cout << "Line 2 - Condition is true"<< endl ;
}

I have tried breaking down the if-expression into two separate statements:

我尝试将if-expression分解为两个单独的语句:

 if (argc==4)  
 {
if(argv[3]="s")
{
       result=no1 - no2;
       cout<<result<<endl;
       return 0;
 }
  }

But if the command, calculator.exe 10 2 d is executed the result is 8, which is incorrect.

但是如果执行命令calculator.exe 10 2 d,则结果为8,这是不正确的。

I would appreciate any help.

我将不胜感激任何帮助。

2 个解决方案

#1


3  

A simple typo: if (argc==4 || argv[3]="s"), the second one is assignment, and will always be true. Change it to testing equality:

一个简单的拼写错误:if(argc == 4 || argv [3] =“s”),第二个是赋值,并且总是为真。将其更改为测试平等:

if (argc==4 || strcmp(argv[3], "s") == 0) //strcmp for c strings
                   ^^^

#2


1  

"argc" is of type int. but argv is pointer array which points to the each argument passed to the program and it stores those as string. and you can't compare strings with ==. So use strcmp instead.

“argc”的类型为int。但是argv是指针数组,它指向传递给程序的每个参数,并将它们存储为字符串。并且您无法将字符串与==进行比较。所以请改用strcmp。

(strcpm(argv[3],"s")==0);  

#1


3  

A simple typo: if (argc==4 || argv[3]="s"), the second one is assignment, and will always be true. Change it to testing equality:

一个简单的拼写错误:if(argc == 4 || argv [3] =“s”),第二个是赋值,并且总是为真。将其更改为测试平等:

if (argc==4 || strcmp(argv[3], "s") == 0) //strcmp for c strings
                   ^^^

#2


1  

"argc" is of type int. but argv is pointer array which points to the each argument passed to the program and it stores those as string. and you can't compare strings with ==. So use strcmp instead.

“argc”的类型为int。但是argv是指针数组,它指向传递给程序的每个参数,并将它们存储为字符串。并且您无法将字符串与==进行比较。所以请改用strcmp。

(strcpm(argv[3],"s")==0);