此代码还有更多内容,但这是唯一不起作用的部分。无论我输入“Change”变量,它都只会给我第一个if语句的代码。我该如何解决这个问题?
std::cout << "Do you want to change any of this information? ";
std::string answer;
std::string x = "yes";
std::cin >> answer;
if(answer == x){
std::cout << "What would you like to change:\nname(1), password(2), email(3), country(4), or cancel(5)?\nType the number of which you want to change: ";
std::cin >> Change;
if(Change = 1){
std::cout << "Please type your new first name: ";
std::cin >> FirstName;
std::cout << "Middle Initial: ";
std::cin >> MiddleInitial;
std::cout << "Last Name: ";
std::cin >> LastName;
std::cout << "Thank you for signing up for Rowan's Demo Company!";
}
if(Change = 2){
std::cout << "Please type your new password: ";
std::cin >> Password;
std::cout << "Thank you for signing up for Rowan's Demo Company!";
}
if(Change = 3){
std::cout << "Please type your new email: ";
std::cin >> Email;
std::cout << "Thank you for signing up for Rowan's Demo Company!";
}
if(Change = 4){
std::cout << "Please type your new country: ";
std::cin >> Country;
std::cout << "Thank you for signing up for Rowan's Demo Company!";
}
if(Change = 5){
std::cout << "Thank you for signing up for Rowan's Demo Company!";
}
}else{
std::cout << "Thank you for signing up for Rowan's Demo Company!";
}
return 0;
}
答案 0 :(得分:2)
啊经典的错误。您无法使用=
进行比较,而是必须使用==
。单个=
用于分配,它总是覆盖您的输入。
评估if
语句if (Change = 1)
的那一刻,Change
得到值1,表达式进一步求值为true
,它将执行{{1}的主体}}
请记住:if
是作业,=
是比较。
答案 1 :(得分:0)
你在 if 中使用 = (赋值运算符)代替 == (比较运算符)进行条件表达式,你也应该在第一级嵌套中使用 if().. else if().. else ! (不是强制性的,但在这里是必要的!) 您也可以在一些if语句中删除块({.......}),因为其中只包含一个语句(为了简化它)! 例如:
两者都会给出相同的结果!
if(a==1)
cout<<" you entered 1";
// or
if(a==1) {
cout<<"you entered 1";
}