如何用C++从txt文件提取字符转int求和及代码异常排查
问题原因
- 未做文件打开成功校验,若文件路径错误/文件不存在,读取不到任何字符,容器为空,
std::accumulate直接返回初始值1,这是你输出结果为1的直接原因 std::accumulate第三个参数是求和初始值,即使读取到内容,填1也会导致最终结果多算1- 代码直接全局读取所有字符,没有筛选每行最后一段的内容,会把前两个字段
Carly、Cat里的a、c等符合a-e的字符也计入求和,导致结果错误 - 没有过滤最后一段末尾的非字母字符(如示例中的
.)
实现逻辑(解决提取最后一段的需求)
- 逐行读取文件内容,而非逐个字符读取
- 对每行字符串,查找最后一个
:的位置,截取该位置之后的子串,即为每行最后一段内容 - 遍历该子串,仅对A-E/a-e范围的字符做转换求和,其余字符直接跳过
修正后完整代码
#include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; int Return_Complexity(char character) { switch (tolower(character)) // 统一转小写,减少重复代码 { case 'a': return 15; case 'b': return 5; case 'c': return 6; case 'd': return 8; case 'e': return 2; default: return 0; } } void printComplexity() { ifstream file("Customers.txt"); if (!file.is_open()) { // 增加文件打开失败判断,避免异常 cout << "文件打开失败,请检查路径是否正确" << endl; return; } int total = 0; string line; while (getline(file, line)) { // 逐行读取 // 查找最后一个冒号的位置 size_t last_colon_pos = line.find_last_of(':'); if (last_colon_pos == string::npos) continue; // 该行无冒号直接跳过 // 截取最后一段内容 string last_part = line.substr(last_colon_pos + 1); // 遍历字符累加结果 for (char c : last_part) { total += Return_Complexity(c); } } cout << total << endl; } int main() { printComplexity(); return 0; }
验证说明
针对你给出的示例Carly:Cat:ABCCCCE.,最后一段截取到ABCCCCE.,计算规则为:15(A)+5(B)+6(C)*4+2(E) = 15+5+24+2=46,和预期结果一致。
内容的提问来源于stack exchange,提问作者bean
相关产品推荐
相关产品推荐

