我最近開始用C++進行編程,在我的學校,州等地進行比賽。我還沒有做過很多練習,而且我對C++還是比較新鮮的,並且遇到了這個問題在我的程序中,如果輸入的是字符而不是數字值,則循環會連續運行而不詢問輸入。最近有這個節目,我寫信給做基本的化學轉化酒吧:如何更正確地將異常集成到我的代碼和未來的代碼中? (C++)
#include "stdafx.h"
using namespace std;
class Exception : public exception
{
public:
Exception(string m = "Exception!") : msg(m){}
~Exception() throw() {}
const char* what() const throw() { return msg.c_str(); }
private:
string msg;
};
int _tmain(int argc, _TCHAR* argv[])
{ // 'n' stands for numerator and 'd' stands for denominator
int choice;
float n1;
float n2;
float n3;
float n4;
float d1;
float d2;
float d3;
float answer;
while (true)
{
cout << "Select how many conversion bars you have: " << endl;
cin >> choice;
if (choice == 1)
{cout << "What is the starting number?" << endl;
cin >> n1;
cout << "What is the first bar (Enter Numerator then Denominator): " << endl;
cin >> n2;
cin >> d1;
answer = n1 * n2/d1;
cout << "Answer: " << answer << endl << endl;}
else if (choice == 2)
{
cout << "What is the starting number?" << endl;
cin >> n1;
cout << "What is the first bar (Enter Numerator then Denominator): " << endl;
cin >> n2;
cin >> d1;
cout << "What is the second bar (Enter Numerator then Denominator): " << endl;
cin >> n3;
cin >> d2;
answer = (n1 * n2 * n3)/(d1 * d2);
cout << "Answer: " << answer << endl << endl;
}
else if (choice == 3)
{
cout << "What is the starting number?" << endl;
cin >> n1;
cout << "What is the first bar (Enter Numerator then Denominator): " << endl;
cin >> n2;
cin >> d1;
cout << "What is the second bar (Enter Numerator then Denominator): " << endl;
cin >> n3;
cin >> d2;
cout << "What is the third bar (Enter Numerator then Denominator): " << endl;
cin >> n4;
cin >> d3;
answer = (n1 * n2 * n3 * n4)/(d1 * d2 * d3);
cout << "Answer: " << answer << endl << endl;
}
else if ((choice /= 1) || (choice /= 2) || (choice /= 3))
{cout << "That is not a valid option." << endl << endl;}
try{ throw Exception();}
catch (exception& e)
{
cout << e.what() << endl;
break;
}
}
return 0;
}
和頭:
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <cstdint>
#include <cstdbool>
#include <string>
那麼我將如何更好地整合例外到這個代碼和任何未來的代碼?例外
這在某種程度上是品味的問題,但在我看來,這不是例外情況。例外情況是出乎意料地發生的事情,很少,_exceptionally_。錯誤的用戶輸入始終發生,並且預期會發生。拋出異常並不是嚴格錯誤(雖然是多餘的),但我認爲這是一個有些尷尬的設計。 – Damon
當你聲明它們時,請開始初始化所有變量!另外,使用名稱空間標準是一個壞習慣,你不應該那樣做。 – crashmstr
1.你會如何建議處理錯誤的用戶輸入, 2.你是什麼意思「初始化」我的變量? (我正在教自己,只是搞亂了代碼) –