当我使用turbo c ++ 4.5进行编程时,我遇到了一个问题,就是将char数组值指定为另一个char数组值作为另一个char数组值作为字符串但是它带有错误
#include <iostream.h>
#include <conio.h>
void main()
{
char txt[16],st[30],w[100];
int i;
i = 0;
while((txt[i++]=getch())!='$');
i--;
st[i] = '\0';
i=0;
while(txt[i]!='$')
{
w = txt;
i++;
}
txt[i] = '\0';
cout <<txt;
if (w == "h"){
cout << " the pass word is:"<<txt;
}
else
{
cout << "incorrect";
}
}
TC 4.5中提到的错误:
函数main()
中需要左值
错误将其指向w
分配给txt
的位置。
答案 0 :(得分:0)
您正在尝试使用数组,就像它们是单个变量一样。在C ++中,它们不是。要复制数组,您必须按成员复制成员。要将它与另一个数组进行比较,您必须按成员比较它。
您可以通过切换
来修复错误 w = txt;
到
w[i] = txt[i];
但不幸的是,这不会让你的代码以你想要的方式工作(它至少会编译)。 使代码工作的更简单方法是重写它以使用字符串而不是数组,因为它们将按照您期望的数组的方式运行。您可以将字符串用作单个变量。
如果出于任何原因想要保留数组,我建议您编写一个函数来比较其中两个,如下所示:
bool equals_strings(char * s1, char * s2){
for (int i = 0;; i++){
if (s1[i] != s2[i])
return false;
if (s1[i] == '\0') // I checked above that they are the same, only need to check one
return true;
}
}
并在您的代码中使用它:
void main()
{
char txt[16], st[30], w[100];
int i;
i = 0;
while ((txt[i++] = getch()) != '$');
i--;
st[i] = '\0';
i = 0;
while (txt[i] != '$')
{
w[i] = txt[i];
i++;
}
txt[i] = '\0';
cout << txt;
if (equals_strings("hello", txt)){ // <- Used it here!
cout << " the pass word is:" << txt;
}
else
{
cout << "incorrect";
}
}
请注意: C ++中的这种代码是致命的,会引发各种各样的麻烦。玩得开心! :d