使用String / Character / Double而不是Integer将使程序循环

时间:2018-12-05 16:09:27

标签: c++

我一直在尝试自己学习C ++(我对伪代码Portugol有所了解),但是遇到了问题。

#include<iostream>
#include<string>

int main(){

//4.3

std::string funcionario[2];
int horas[2], depen[2];
const double INSS=0.085, IRS=0.05;

for (int i=0 ; i<2 ; i++) {
   std::cout << "Indique o nome do " << i+1 << "º funcionário, o número de 
 horas e dependentes"
            << '\n' << "Funcionário_" << i+1 <<": ";
  std::cin >> funcionario[i];
  std::cout << "Horas: ";
  std::cin >> horas[i];

    while (horas[i]<0) {
      std::cout << "Ups! Algo deu errado, tente novamente." << '\n' << 
"Horas: ";
      std::cin >> horas[i];
      }

   std::cout << "Dependentes: ";
   std::cin >> depen[i];
    while (depen[i]<0) {
      std::cout << "Ups! Algo deu errado, tente novamente." << '\n' << 
 "Dependentes: ";
      std::cin >> depen[i];
    }
  std::cout << '\n' << '\n';
}
for (int i=0; i<2; i++) {
  std::cout << "Funcionário " << funcionario[i] << ": " << '\n'
            << "Salário Bruto: " << horas[i]*12+depen[i]*40 << "€" << '\n'
            << "Salário Líquido: " << (horas[i]*12+depen[i]*40)- 
   ((horas[i]*12+depen[i]*40)*INSS + (horas[i]*12+depen[i]*40)*IRS)
            << "€" << '\n' << "Descontos-INSS: "<< 
    (horas[i]*12+depen[i]*40)*INSS
            << "€" << '\n' <<'\t' << "  IRS: " << 
    (horas[i]*12+depen[i]*40)*IRS << "€";
  std::cout << '\n' << '\n';

}

}

在尝试程序时,我注意到是否在“ std :: cin >> horas [i];”上写了一个字符串而不是一个整数。和“ std :: cin >> depen [i];”我将得到一个循环like this或一些奇怪的值like this

我已经尝试过:

#include<limits>

...

while (horas[i]<0) {
    while(!(cin >> horas[i])) {
        cout << "Incorrect input. Please try again.\n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

      std::cout << "Ups! Algo deu errado, tente novamente." << '\n' << 
"Horas: ";
      std::cin >> horas[i];
       }

但是我不知道它是如何工作以及如何使用的,我只是遇到编译错误。

我该如何解决?

谢谢!

0 个答案:

没有答案