C++ 輸入類型不匹配檢測方法
C++中檢測輸入類型不匹配的檢測方法。
輸入類型不匹配是指輸入的數據類型與所期望的類型不匹配,如 int n; cin >> n; 但輸入的數據為字符串時,這
種情況就是輸入類型不匹配。那么當出現這種情況時,變量n的值有沒有改變呢,又該如何檢測這種情況呢?
首先
- 變量n的值并沒有改變。
- 不匹配的字符串仍留在輸入緩沖區中。
- cin類中的一個錯誤標志被設置了
- cin方法轉換成的bool類型返回值為false
檢測方法:
如下面的示例程序,首先用 good() 方法檢測輸入是否出錯,然后分別檢測出錯類型,先檢測是否遇到EOF,使用 eof() 方法,
然后檢測是否出現輸入類型不匹配的情況,使用 fail() 方法,注意 fail()方法在當遇到 EOF 或者出現輸入類型不
匹配時都返回true。
還可以使用bad()方法檢測文件損壞或硬件錯誤而出現的輸入錯誤。
// sumafile.cpp -- functions with an array argument
#include <iostream>
#include <fstream> // file I/O support
#include <cstdlib> // support for exit()
const int SIZE = 60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream inFile; // object for handling file input
cout << “Enter name of data file: “;
cin.getline(filename, SIZE);
inFile.open(filename); // associate inFile with a file
if (!inFile.is_open()) // failed to open file
{
cout << “Could not open the file “ << filename << endl;
cout << “Program terminating.\n”;
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0; // number of items read
inFile >> value; // get first value
while (inFile.good()) // while input good and not at EOF
{
++count; // one more item read
sum += value; // calculate running total
inFile >> value; // get next value
}
if (inFile.eof())
cout << “End of file reached.\n”;
else if(inFile.fail())
cout << “Input terminated by data mismatch.\n”;
else
cout << “Input terminated for unknown reason.\n”;
if (count == 0)
cout << “No data processed.\n”;
else
{
cout << “Items read: “ << count << endl;
cout << “Sum: “ << sum << endl;
cout << “Average: “ << sum / count << endl;
}
inFile.close(); // finished with the file
return 0;
} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!