无法在函数main中编译,需要Lvalue

Cannot compile, Lvalue required, in function main

本文关键字:编译 需要 Lvalue main 函数      更新时间:2023-10-16

我想编译这个,但它给了我错误,即使我更改了引号,头文件中是否有任何错误,请告诉我

#include<iostream.h>
#include<conio.h>

void main()
{
char st[20];
cin>>st;

cout<<st<<endl;
if (st = 'a')
cout<<"This is a";

if (st = 'b')
cout<<"This is b";
getch();
}

以下内容不太正确:

if (st = 'a')
if (st = 'b')

首先,=是赋值,而不是比较。第二,CCD_ 2和CCD_ 3是CCD_。

写以上内容的正确方法是

if (strcmp(st, "a") == 0)
if (strcmp(st, "b") == 0)

也就是说,我鼓励您不再使用C字符串,而是使用std::string

=不用于比较,

if (st = 'a') 

if (st = 'b')

它将尝试改变st,并且以上比较的结果总是true

尝试使用std::string:

#include <string>
...
std::string st;
std::cin >> st;
cout<<st<<endl;
if (st == "a")
  cout<<"This is a";

if (st == "b")
  cout<<"This is b";
if (st = 'a')
if (st = 'b')

在上面的两行中,l-value(左值('st'都指向数组的开头,并且不能更改其地址。这就是为什么在编译中会出现l-value错误的原因。使用相等(==(运算符而不是赋值(=(和取消引用st来更改If条件,以在开头获取值。

if (*st == 'a')
if (*st == 'b')

好吧,在我的学习线上。您正在使用赋值运算符"="导入string.h指令,并使用该库的strcmp();函数希望这对有帮助