C++堆栈:未初始化的局部变量

问题描述:

#include "iostream" 
using namespace std; 

int main() 
{ 
int a,d,D,c,C,b,B,r,R; 
char f,y,Y,n,N; 

cout << "Press D - d, for dog,C -c for cat, B - b, for bird or R - r for Reptile:"; 
cin >> a; 

if (a == d || a == D || a == c || a == C || a == b || a == B || a == r || a == R); 

     if (a == d || a == D || a == c || a == C) 

       if (a == d || a == D) 
       cout << "Is it neutered(Y/N)"; 
     cin >> f; 
     if (f == Y || f == y) 
       cout << "50 Euros."; 
     else if (f == n || f == N) 
       cout << "80 Euros."; 

     if (a == c || a == C) 
       cout << "Is it neutered(Y/N)"; 
     cin >> f; 
     if (f == Y || f == y) 
       cout << "40 Euros."; 
     else if (f == n || f == N) 
       cout << "60 Euros."; 
     if (a == r || a == R || a == B || a == b) 
       cout <<"10 Euros."; 

if (a != d && a != D && a != c && a != C && a != b && a != B && a != r && a != R) 
       cout << "Error!"; 

     system("pause"); 


     return 0;} 

错误我得到:C++堆栈:未初始化的局部变量

...\12b.cpp(21): warning C4390: ';' : empty controlled statement found; is this the intent? 
...\12b.cpp(20): error C4700: uninitialized local variable 'd' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'D' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'c' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'C' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'b' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'B' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'r' used 
...\12b.cpp(20): error C4700: uninitialized local variable 'R' used 
...\12b.cpp(25): error C4700: uninitialized local variable 'Y' used 
...\12b.cpp(25): error C4700: uninitialized local variable 'y' used 
...\12b.cpp(27): error C4700: uninitialized local variable 'n' used 
...\12b.cpp(27): error C4700: uninitialized local variable 'N' used 

为什么会出现这个错误?我不明白?

+0

嗯,因为你没有初始化任何变量,所以你使用了它们,并且在你的if语句结尾处有';'。 – 2013-04-06 21:42:16

+1

我认为你对输入有一个重大的误解。你认为由'int a,d,D,c,C,b,B,r,R'定义的变量与用户的输入有什么关系?除了'a'之外,你不使用它们中的任何一个。 – 2013-04-06 21:43:49

+0

请直接在您的问题中发布代码,而不是外部链接。 – 2013-04-06 21:44:08

好吧,让我们让这段代码更容易。我认为你打算做的是这样的:

char selection; 
cout << (as before) 
cin >> selection; 

selection = tolower(selection); 

switch(selection) { 
case 'd': 
    // stuff for dogs here 
    break; 
case 'c': 
    // stuff for cats 
    break; 
// etc. 
default: 
    // error case 
} 

对不对?

+0

+1友好的回答,甚至有帮助! – Walter 2013-04-06 22:06:54

我认为这是很清楚,而不是

if (a == d || ... 

你真正想要

if (a == 'd' || ... 

即要变a与字符'd'比较。你多次犯过同样的错误,所以修复它们,看看有什么错误。

此外,您错误地将a作为int应该是char。由于某种原因,您对f适用,但对a不适用。