让变量忘记以前的值?

时间:2015-10-08 04:03:50

标签: c++

我有一个非常恼人的问题。

首先,我编写了一个只运行一次的程序,一切都很完美,直到我决定用用户输入重新执行它。

现在我遇到了大麻烦。当我重新执行程序时,它会落入错误的开关或if语句,因为变量不会重新初始化。描绘它:

// Libraries and other stuff

int numA, numB, numC;
char charA = 'A', charB = 'B', charC = 'C';

int main() {

do {

// Randomly assigning some numbers between 1-3 range into numA, numB and numC

...

// Converting the integers above into chars depending on the random numbers

switch (numA)
{
  case 1:
  numA = charA;
  break;

  case 2:
  numA = charB;
  break;

  case 3
  numA = charC;
  break;
}

switch (nu...

...

// A lot of IFs and SWITCHs that consistently changes the values above within themselves.

...

// Taking 1 input from user to re-execute the program

} while (input == 1)

return 0;

}

我知道我搞砸了所有事情并没有正确地初始化变量,但是当我开始创建它时我还没有计划让它重新执行,现在我正在寻找最佳的方法来逃逸。我可以以某种方式使变量忘记它们携带的先前值吗?或者我真的需要从头开始重新初始化所有内容吗?

2 个答案:

答案 0 :(得分:1)

将变量的声明移动到循环内的范围内,以便在每次传递时重新初始化它们。

int main() {

do {
//new scope
{
int numA, numB, numC;
char charA = 'A', charB = 'B', charC = 'C';

// Randomly assigning some numbers between 1-3 range into numA, numB and numC

...

// Converting the integers above into chars depending on the random numbers

switch (numA)
{
  case 1:
  numA = charA;
  break;

  case 2:
  numA = charB;
  break;

  case 3
  numA = charC;
  break;
}

switch (nu...

...

// A lot of IFs and SWITCHs that consistently changes the values above within themselves.

...

// Taking 1 input from user to re-execute the program
}//end of scope
} while (input == 1)

但是您应该理解,未初始化变量的使用是未定义的行为,应始终避免使用。

此外,您的char变量初始化(char charA = 'charA')完全无效。您不能在一个字符变量中存储6个字符串(5个字符和空终止符)。您应该使用char*或者这是简单的印刷错误,它应该是char charA = 'A'

答案 1 :(得分:0)

您将所有字符初始化为'c'。当你将所有字符初始化为'charA','charB'和& 'charC'但在初始化字符时,它只需要一个字符,如char ch1= '6', ch2='\n' ; 因为所有初始值设定项的首字母都是'c'。这就是所有初始化为'c'的原因 你也忘记了()的分号。
您还使用numA作为开关控制变量。 &安培;在switch语句中,你正在更改numA中的值。这没有错,但是做法不好。很抱歉很多编辑,因为我在stackexchange应用程序,我需要多次看到问题。

相关问题