关于将char数组分配给另一个char数组变量时的左值 当我用Turbo C++ 4.5编程时,当把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"; } } #包括 #包括 void main() { char-txt[16],st[30],w[100]; int i; i=0; 而((txt[i++]=getch())!=“$”); 我--; st[i]='\0'; i=0; 而(txt[i]!=“$”) { w=txt; i++; } txt[i]='\0'; CUT你试图使用数组,就像它们是一个变量。在C++中,它们不是。要复制一个数组,必须按成员来复制它。要与另一个数组进行比较,必须将它按成员进行比较。
您可以通过切换来修复错误关于将char数组分配给另一个char数组变量时的左值 当我用Turbo C++ 4.5编程时,当把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"; } } #包括 #包括 void main() { char-txt[16],st[30],w[100]; int i; i=0; 而((txt[i++]=getch())!=“$”); 我--; st[i]='\0'; i=0; 而(txt[i]!=“$”) { w=txt; i++; } txt[i]='\0'; CUT你试图使用数组,就像它们是一个变量。在C++中,它们不是。要复制一个数组,必须按成员来复制它。要与另一个数组进行比较,必须将它按成员进行比较。,c++,arrays,C++,Arrays,您可以通过切换来修复错误 w = txt; 到 但不幸的是,这并不能使您的代码按您希望的方式工作(至少它会编译)。 使代码工作的更简单的方法是重写代码,使其与字符串而不是数组一起工作,因为它们的行为方式与您期望的数组相同。您可以将字符串用作单个变量 如果出于任何原因想要保留数组,我建议您编写一个函数来比较其中的两个,如下所示: bool equals_strings(char * s1, char * s2){ for (int i = 0;; i++){ if (s
w = txt;
到
但不幸的是,这并不能使您的代码按您希望的方式工作(至少它会编译)。
使代码工作的更简单的方法是重写代码,使其与字符串而不是数组一起工作,因为它们的行为方式与您期望的数组相同。您可以将字符串用作单个变量
如果出于任何原因想要保留数组,我建议您编写一个函数来比较其中的两个,如下所示:
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";
}
}
void main()
{
char-txt[16],st[30],w[100];
int i;
i=0;
而((txt[i++]=getch())!=“$”);
我--;
st[i]='\0';
i=0;
而(txt[i]!=“$”)
{
w[i]=txt[i];
i++;
}
txt[i]='\0';
实际上,这是在Turbo C++中运行的,所以STD没有定义,那么,使用任何一个编译器,你使用传统Turbo C++编译器的原因是什么?你不能分配数组。你可以写一个循环来拷贝元素,或者使用<代码> MeMCPY < /COD>。使用旧的编译器?它们与新的编译器没有多大区别,但在语法上没有多大区别,对吗?
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";
}
}