我的简单'if'语句没有执行代码中的内容

My simple 'if' statement isn't doing what's in the code

本文关键字:代码 执行 简单 if 语句 我的      更新时间:2023-10-16

在这一小段代码中,我收集来自用户的输入数据。如果给出的第一个输入是"0",则不接受更多信息,如果不是"0",则提示输入其余数据。

class Molecule {
char structure[10];
char name[20];
double weight;
public:
Molecule();
bool read();
void display() const;
};
bool Molecule::read() {

cout << "Enter structure : ";
cin >> structure;
if (structure != "0") {
cout << "Enter name : ";
cin >> name;
cout << "Enter weight : ";
cin >> weight;
}
}

表示,如果结构不为0,则提示输入其余信息。但是当我运行这个程序时它显示了另一个cout和cin,即使我输入0。为什么它没有做它应该做的事情?

问题是你正在尝试对字符串值进行比较,但你实际上是在对指针值进行比较。您需要使用像strcmp这样的函数来获取值比较语义

if (strcmp(structure, "0") != 0) {
  ...
}

您编写的原始代码有效地执行了以下操作

int left = structure;
int right = "0";
if (left != right) { 
  ...
}

我已经掩盖了一些细节(包括架构),但本质上这是你的原始样本正在做的。C/c++并没有真正的字符串值概念。它对字符串字面值以及如何将它们转换为char数组有有限的理解,但不知道应该如何理解这些值。

展开我的评论

使用

#include <string>
...
std::string structure;
...
structure="foo";
....
if(structure == "foo")
{
   ...
}