【发布时间】:2016-07-14 18:30:27
【问题描述】:
你好,这不是我的全部代码,但我被困在这个地方,只有当用户输入“NewYork”这个词时我才需要打印信息,并且当我调试时,即使我输入“NewYork”这个词也不会打印任何内容.那么任何人都可以告诉可能是什么问题吗?谢谢
int main(){
Panel *panelptr;
int count,len,wid;
double heg;
char locat[30];
cout<<"how many panels do you need to create ? "<<endl;
cin>>count;
panelptr = new Panel[count];
assert(panelptr!=0);
for(int i=0; i< count; i++){
cout << "Enter the length: ";
cin >>len;
cout << "Enter the width: ";
cin >> wid;
cout << "Enter the height: ";
cin >> heg;
cout<<"Enter the location: ";
cin >>locat;
panelptr[i].setPanel(len,wid,heg,locat);
if(locat == "NewYork")
panelptr->print();
}
delete [] panelptr;
system("pause");
return 0;
}
【问题讨论】:
-
您正在比较 char* 的指针值,而不是实际内容。尝试使用 std::string 而不是 char[]
-
这条语句
if(locat == "NewYork")实际上比较了两个永远不会相同的char*指针。 -
无法使用
==运算符比较数组。如果您坚持将locat与字符串文字“NewYork”(使用数组表示)进行比较,请查找strcmp()函数。更好的是,使用在标准头<string>中指定的 C++ 标准字符串类 (std::string) 而不是char的数组。
标签: c++ if-statement char