我的简单'if'语句没有执行代码中的内容
My simple 'if' statement isn't doing what's in the code
在这一小段代码中,我收集来自用户的输入数据。如果给出的第一个输入是"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")
{
...
}
相关文章:
- 以下代码执行哪种内存分配(动态或静态)?
- 允许多个互斥锁所有者或指定数量的并发代码执行
- 使用 execv 从C++代码执行的 Linux 脚本失败
- 由于找不到cpprest_2_10.dll,代码执行无法继续
- 在每次循环迭代时停止代码执行毫秒
- 与Java相比,为什么此C 代码执行速度如此慢
- 记录组件代码执行
- 相同的代码执行两次:性能差异
- 代码执行/CPU 速度每 2 秒减慢一次
- 函数返回本地变量,尽管变量不超出范围,没有编译器问题,并且代码执行
- 如何将字符串从C++DLL返回到MetaTrader 4代码执行生态系统?
- 当我从java代码执行C++时不显示任何输出
- C++和共享库中的代码执行点
- 递归期间代码执行中断
- 为可选的评测代码执行进行高效设计
- 我正在尝试使用 ifstream 将此 C 函数的等效代码执行到 c++ 中
- 最佳C 11测量嵌入式系统代码执行时间的方法
- 如何在iOS应用程序中锁定代码执行
- 中断代码执行
- 是否有一个工具来记录代码执行