簡單錯誤記錄/華為機試(C/C++)
阿新 • • 發佈:2019-02-10
題目描述
開發一個簡單錯誤記錄功能小模組,能夠記錄出錯的程式碼所在的檔名稱和行號。
處理:
1、 記錄最多8條錯誤記錄,迴圈記錄,對相同的錯誤記錄(淨檔名稱和行號完全匹配)只記錄一條,錯誤計數增加;
2、 超過16個字元的檔名稱,只記錄檔案的最後有效16個字元;
3、 輸入的檔案可能帶路徑,記錄檔名稱不能帶路徑。
輸入描述:
一行或多行字串。每行包括帶路徑檔名稱,行號,以空格隔開。
輸出描述:
將所有的記錄統計並將結果輸出,格式:檔名 程式碼行數 數目,一個空格隔開,如:
示例1
輸入
E:\V1R2\product\fpgadrive.c 1325
輸出
fpgadrive.c 1325 1
程式碼1:
//第十九題 錯誤記錄 #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; typedef struct item { string filename; int num_line; int num_fre; bool operator== (const item& item) { if (item.filename == filename && item.num_line == num_line) return true; return false; } }; int main() { int inum = 0; vector<item>v_record; string in_str; int i_num_line; while (cin>> in_str>> i_num_line) { size_t last_position = in_str.find_last_of('\\'); if (last_position != string::npos) { string filename = in_str.substr(last_position + 1, in_str.length() - last_position - 1); if (filename.length() > 16) { filename = filename.substr(filename.length() - 16); } item temp{ filename ,i_num_line ,1}; vector<item>::iterator it; if ((it=find(v_record.begin(), v_record.end(), temp)) != v_record.end()) { it->num_fre += 1; } else v_record.push_back(temp); } else { break; } } int i_max = v_record.size(); int i_min = i_max - 8; i_min = i_min > 0 ? i_min : 0; for (int i = i_min; i < i_max; i++) { cout << v_record[i].filename.c_str() << " " << v_record[i].num_line << " " << v_record[i].num_fre << endl; } system("pause"); return 0; }
3ms
程式碼2:
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; typedef struct item { string filename; int line; int cnt; bool operator== (const item& item) { if (item.filename == filename && item.line == line) return true; return false; } }; // 獲取淨檔名的最後16個字元 string get_filename(string filename) { string ret; int index = filename.find_last_of('\\', filename.size() - 1); if (index == -1) ret = filename; else ret = filename.substr(index + 1); if (ret.size() > 16) ret = ret.substr(ret.size() - 16); return ret; } int main(void) { string filename; int line; vector<item> log; while (cin >> filename >> line) { filename = get_filename(filename); vector<item>::iterator it; item tmp = { filename, line, 1 }; if ((it = std::find(log.begin(), log.end(), tmp)) != log.end()) (*it).cnt++; else log.push_back(tmp); } int start_index = log.size() - 8; if (start_index < 0) start_index = 0; for (int i = start_index; i < log.size(); ++i) cout << log[i].filename << " " << log[i].line << " " << log[i].cnt << endl; system("pause"); return 0; }