0
只是想知道如何防止用戶輸入錯誤的輸入,如輸入cookie時,該變量是一個雙精度而不是字符串。例如在我的代碼中,我正在使用一個文本文件,該文件將被我的程序讀取,該文件將從Data.txt中獲取所有信息並將其放入像RecWidth這樣的變量中。有來自試圖進入RecWidth使得像餅乾字符串的方式只是導致RecWidth是一個0如何防止一個字符串輸入一個雙變量和搞亂程序
#include <cstring>
#include <fstream>
#include <iostream>
#include <cmath>
using namespace std;
int main() {
std::ifstream input_file("Data.txt", ios::in);
ofstream out_data("Output.txt", ios::out);
int age = 0;
int totalAge = 0;
double RecLength, RecWidth, RecArea, RecPerimiter, CirRadius, CirCricumfrence = 0;
double totalWidth = 0;
double totalLength = 0;
double totalPerimiter = 0;
double totalSavings = 0;
double totalArea = 0;
double totalRadius = 0;
double totalCArea = 0;
double totalCircumfrence = 0;
double CirArea, Savings, NumberOfPeople = 0;
string NameFirst, NameLast;
while (!input_file.eof())
{
input_file >> RecLength;
input_file >> RecWidth;
totalLength = totalLength + RecLength;
totalWidth = totalWidth + RecWidth;
RecArea = RecLength * RecWidth;
totalArea = totalArea + RecArea;
RecPerimiter = (RecLength * 2) + (RecWidth * 2);
totalPerimiter = totalPerimiter + RecPerimiter;
input_file >> CirRadius;
totalRadius = totalRadius + CirRadius;
CirCricumfrence = 2 * M_PI * CirRadius;
totalCircumfrence = totalCircumfrence + CirCricumfrence;
CirArea = M_PI * pow(CirRadius, 2.0);
totalCArea = totalCArea + CirArea;
input_file >> NameFirst;
input_file >> NameLast;
NumberOfPeople++;
input_file>> age;
totalAge = totalAge + age;
input_file>> Savings;
totalSavings = totalSavings + Savings;
}
out_data << "Rectangle:" << endl << "The total lengths= " << totalLength << ", width= " << totalWidth << ", area= " << totalArea << ", perimeter= " << totalPerimiter << endl << endl;
out_data << "Circle:" << endl << "The total Radius= " << totalRadius << ", area= " << CirArea << ", circumfrence= " << CirCricumfrence << endl << endl;
out_data << "Person:" << endl << "Total number of persons= " << NumberOfPeople << endl << "Total age= " << totalAge << endl << "The total saving= " << totalSavings << endl << endl;
return 0;
}
你應該張貼在威脅建模部這個問題。 – Nandu
您應該在威脅建模部分發布此問題。 – Nandu
我認爲你可以編輯你的問題,並做得更簡潔。基本上,據我所知,你想驗證輸入數據類型與聲明的類型匹配 – lrleon