2013-09-24 25 views
1
int f =0; 
    std::cout << " do you want to use 1. component y or n " << std::endl; 
    std::cin >>f; 
    if(f == 'y' || f =='n'){ 
     if (f =='y'){ 
      this->decisionvector[0] = 1; 
     }else 
      this->decisionvector[0] = 0; 

    } 

    std::cout << " do you want to use 2. component y or n " << std::endl; 
    std::cin >>f; 
    if(f == 'y' || f=='n'){ 
     if (f =='y'){ 
      this->decisionvector[1] = 2; 
     }else 
      this->decisionvector[1] = 0; 
     f= 0; 
    } 
    std::cin.clear(); 
    std::cout << " do you want to use 3. component y or n " << std::endl; 
    std::cin >>f; 
    if(f == 'y' || f =='n'){ 
     if (f =='y'){ 
      this->decisionvector[2] = 4; 
     }else 
      this->decisionvector[2] = 0; 
     f= 0; 
    } 
    std::cin.clear(); 
    std::cout << " do you want to use 4. component y or n " << std::endl; 
    std::cin >>f; 
    if(f == 'y' || f =='n'){ 
     if (f =='y'){ 
      this->decisionvector[3] = 8; 
     }else 
      this->decisionvector[3] = 0; 
     f= 0; 
    } 

为什么我只能在第一个if语句中设置f,程序不会停止在其他程序中?这部分C++代码有什么问题?

+7

在第二个块中,您正在读入'k',但比较了'f'。这显然是错误的。 –

+0

我编辑过的代码仍然是同样的问题 – Engine

+0

用调试器遍历代码,看看发生了什么。 –

回答

3

你应该改变int fchar f

+0

好吧,但为什么? – Engine

+0

我只是猜测,但它的第一件事是关于char和int的物理尺寸(8位,16位是unicode,4位是int)。是的,你可以用一个数字来检查一个字符,比如'c'== 35,但是我不认为用int变量做安全和正确。 – IssamTP

+1

@Engine'std :: cin :: operator >>(int&)'将解析字符序列为一个整数值。 'std :: operator >>(istream&is,char&c)'将提取该字符并将其值存储为*。 – zakinster

0

在你读数来说,K,但用y中的第二块...

std::cin >>k; 
if(k == 'y' || k=='n'){ 
    if (f =='y'){ 
     this->decisionvector[1] = 2; 
    }else 
     this->decisionvector[1] = 0; 
    f= 0; 
} 
2
int f =0; 
std::cin >>f; 

std::cin读取和解释字符的序列。

如果fint,它将使用提取运算符operator>>int超负荷。该运算符将尝试将输入格式化为整数。

如果用户通过字符'y',操作员将无法将其解释为整数并将存储0f。您可以使用cin.fail()检查流的错误状态。

如果你想读一个字符,你必须使用一个char