C 輸入型別不匹配檢測方法

2021-08-27 13:17:32 字數 1261 閱讀 6501

今天看c++ primer plus一書,看到c++中檢測輸入型別不匹配的檢測方法。

輸入型別不匹配是指輸入的資料型別與所期望的型別不匹配,如 int n; cin >> n; 但輸入的資料為字串時,這

種情況就是輸入型別不匹配。那麼當出現這種情況時,變數n的值有沒有改變呢,又該如何檢測這種情況呢?

首先檢測方法:

如下面的示例程式,首先用good()方法檢測輸入是否出錯,然後分別檢測出錯型別,先檢測是否遇到eof,使用eof()方法,

然後檢測是否出現輸入型別不匹配的情況,使用fail()方法,注意fail()方法在當遇到eof或者出現輸入型別不

匹配時都返回true。

還可以使用bad()方法檢測檔案損壞或硬體錯誤而出現的輸入錯誤。

// sumafile.cpp -- functions with an array argument

#include #include // file i/o support

#include // support for exit()

const int size = 60;

int main()

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

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

infile.close(); // finished with the file

return 0;

}

scanf 函式的引數輸入型別不匹配問題

scanf 函式的引數輸入型別不匹配問題 這是我在csdn論壇上見到的問題,這個錯誤有時候會讓人莫名其妙。include main 當輸入a 回車 後,會直接跳過下面 個scanf語句,直接輸出為 123 t 原因 對於scanf d c a,c scanf語句執行時,首先試圖從緩衝區中讀入乙個 d...

scanf和cin輸入型別不匹配時造成的死迴圈問題

下面兩段 要實現的功能是往整數變數i中輸入乙個資料,輸入數字1時退出,然而當輸入乙個字元時,整個程式會變成乙個死迴圈。c int i 0 while i 1 c語言 int i 0 while i 1 原因 造成死迴圈的原因也很簡單,當第一次通過scanf函式讀入整數時,如果我們輸入的是乙個字元,那...

Codeigniter檔案上傳型別不匹配錯誤

codeigniter的檔案上傳類方便了我們使用php來處理檔案上傳的操作,使用起來非常簡單,如下 如果只是處理型別的檔案,基本上不會遇到這個坑,如果處理到了 excel zip rar型別的檔案,你可能就會遇到明明在 allowed types 中允許的檔案型別,最後收穫了 the filetyp...