gpt4 book ai didi

c++ - 在切换情况下声明后,C++变量不会更改

转载 作者:行者123 更新时间:2023-12-03 07:22:24 26 4
gpt4 key购买 nike

我仍在学习C++。我想编写一个默认值为O和X的代码。但是用户可以自己更改它,而两个值不能相同,也不能使用某些特殊符号。如果存在任何错误,则该值将重置为O和X。但是,在其中一种情况下重置该值之后,该变量仍包含错误值。希望我能从这里得到一些提示。这是我的代码。

int main()
{
string s1 = "O";
string s2 = "X";
//User Interface
cout << "*** Menu***" << endl;
cout << "[1] " << endl;
cout << "[2] " << endl;
cout << "*****************" << endl;

//Select Option
string option; //For input
int o; //For switch statement

cout << "Option (1 - 2):";
getline(cin, option);

switch (o) {
case 1: {
} break;
case 2: {
cout << "[1] " << endl;
cout << "[2] " << endl;
;
cout << "Option (1 - 2):";
string optionstring;
getline(cin, optionstring);

switch (optionstring[0]) {
case '1': {
break;
}

case '2': {
cout << endl
<< "current s1 =" << s1 << "Current s2 =" << s2 << endl
<< endl;
bool check = true;
while (check) {
check = false;
string change; // For switch
char c; // For switch statement

cout << "Do you want to change the value? (Type Y to change or N to return to settings menu)?";

getline(cin, change);
if (change.size() > 1)
c = 'f'; //Indicates invalid input
else
c = change[0];

switch (c) {

case 'Y':
cout << endl
<< "Input new symbol for s1." << endl;

cout << "new symbol for s1:" << endl;
getline(cin, s1);
if (!(s1.size() == 1) || (s1 == "+") || (s1 == "-") || (s1 == "|")) {
string s1 = "O";
string s2 = "X";
cout << endl
<< "The current setting has been reset to checker symbols‘" << s1 << "’for s1, ‘" << s2 << "’for s2)." << endl
<< endl;
continue;
}
cout << endl
<< "current s1 =" << s1;
break;
}
当我在s1中输入“+”时,将显示一条错误消息,并且该值将重置为O,最后一行代码可以显示它已成功重置。但是在再次运行该案例之后,s1值仍然包含错误值,例如“+”。需要一些帮助!!

最佳答案

如果我对您的问题的解释正确,则应该可以进行以下操作。在这段代码中,您将创建新的临时变量s1和s2。

if (!(s1.size() == 1) || (s1 == "+") || (s1 == "-") || (s1 == "|")) {
string s1 = "O";
string s2 = "X";
...
尝试避免声明新变量,如下所示:
    if (!(s1.size() == 1) || (s1 == "+") || (s1 == "-") || (s1 == "|")) {
s1 = "O";
s2 = "X";
...

关于c++ - 在切换情况下声明后,C++变量不会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64750466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com