c++ 键入错误类型时抛出异常

ufj5ltwl  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(162)

我必须写一个C++程序,其中的一个函数是从键盘上读取两个double类型的数字,并添加一个try块,当键入错误的类型时抛出异常。我使用了cin.fail()函数,但它没有工作。
这是我目前为止尝试过的,但是如果我输入双精度值,它不会抛出异常。

  1. #include<iostream>
  2. #include<conio.h>
  3. using namespace std;
  4. int main()
  5. {
  6. double j;
  7. try{
  8. cin>>j;
  9. if (cin.fail())
  10. throw (j);
  11. else
  12. cout << "Double Value " << j << endl;
  13. }
  14. catch(double a)
  15. {
  16. cout<<"Incompatible Datatype for value"<<a;
  17. }
  18. }
az31mfrm

az31mfrm1#

那么捕获字符串并处理异常呢?以下是总体思路:

  1. string d;
  2. try{
  3. cin >> d;
  4. if ( d.find_first_not_of("0123456789-+.") != string::npos)
  5. {
  6. throw std::runtime_error("not an int");
  7. }
  8. else if ( ( strtod( d.c_str(),nullptr ) > INT_MAX ) || ( strtod( d.c_str(),nullptr ) < INT_MIN ) )
  9. {
  10. throw std::runtime_error(" int overflow");
  11. }
  12. }
  13. catch(const std::exception&d)
  14. {
  15. cout << d.what() << endl;
  16. }
展开查看全部
jhiyze9q

jhiyze9q2#

  1. #include <iostream>
  2. using namespace std;
  3. double a, b;
  4. void accept()
  5. {
  6. cout << "Enter any two Numbers\n";
  7. try
  8. {
  9. cin >> a;
  10. if (cin.fail())
  11. throw(a);
  12. cin >> b;
  13. if (cin.fail())
  14. throw(b);
  15. }
  16. catch (...)
  17. {
  18. cout << "Incompatible Datatype for value\n";
  19. exit(0);
  20. }
  21. }
  22. int main()
  23. {
  24. accept();
  25. return 0;
  26. }

我想这会有用的。

展开查看全部
20jt8wwn

20jt8wwn3#

这个5年前的问题有两种方法:try/catch和阅读failbit

  1. #include <iostream>
  2. #include <string>
  3. #include <limits>
  4. int main()
  5. {
  6. /* Using try/catch */
  7. std::string a;
  8. double A;
  9. std::cout << "Digit A: "; std::getline(std::cin, a);
  10. try // Try to execute code below without problem
  11. {
  12. A = stod(a); // stod, string-to-double
  13. std::cout << A << std::endl;
  14. }
  15. catch (std::invalid_argument&) // Catch when a specific problem occurs
  16. {
  17. std::cout << "Invalid first digit" << std::endl;
  18. }
  19. /* Another way; std::cin >> double, catch if fail when input isn't double */
  20. double B;
  21. std::cout << "Digit B: "; std::cin >> B;
  22. if (std::cin.fail()) // If failbit is set, clear the failbit flag and clear input buffer until it hits '\n'*
  23. {
  24. // https://gist.github.com/leimao/418395bf920eb70b2b11fe89d7c1f738
  25. std::cin.clear();
  26. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  27. std::cout << "Invalid second digit" << std::endl;
  28. }
  29. else
  30. {
  31. std::cout << B << std::endl;
  32. }
  33. return 0;
  34. }

要注意的是,当至少第一个输入的字符是正确的类型而其余的不是(特别是对于十进制类型)时,变量值赋值仍然进行,并且丢弃从第一个不同类型字符开始的其余输入。这意味着在这种情况下,Digit A: 123F5变成123

展开查看全部

相关问题