C++如何读取txt文件字符转换为整数并计算指定字符段的数值总和
C++ 读取txt文件指定段字符并计算数值总和实现方案
实现逻辑
- 引入文件操作、字符串处理相关头文件
- 读取txt文件的整行内容
- 按冒号
:分割字符串,取第三段内容(即包含目标字符的部分) - 去除第三段末尾的
.字符,得到目标字符串ABCCCCE - 遍历目标字符串的每个字符,调用你已实现的
getComplexity函数累加数值
完整可运行代码
#include <iostream> #include <fstream> #include <string> #include <vector> // 你已经实现的字符转数值函数 int getComplexity(char theCode) { int complexity; if(theCode == 'A') { complexity = 1; } else if(theCode == 'B') { complexity = 2; } else if(theCode == 'C') { complexity = 3; } else if(theCode == 'D') { complexity = 4; } else if(theCode == 'E') { complexity = 5; } // 增加默认值避免遇到其他字符出现未定义行为 else { complexity = 0; } return complexity; } int main() { // 1. 打开txt文件,这里替换成你的实际文件路径 std::ifstream inputFile("test.txt"); if (!inputFile.is_open()) { std::cout << "文件打开失败,请检查路径是否正确" << std::endl; return 1; } // 2. 读取文件整行内容 std::string lineContent; std::getline(inputFile, lineContent); inputFile.close(); // 3. 按冒号分割字符串,提取第三段内容 std::vector<std::string> parts; std::string temp; for (char c : lineContent) { if (c == ':') { parts.push_back(temp); temp.clear(); } else { temp += c; } } parts.push_back(temp); // 把最后一段内容加入容器 if (parts.size() < 3) { std::cout << "文件内容格式不符合要求" << std::endl; return 1; } std::string targetPart = parts[2]; // 4. 去掉末尾的.字符 if (targetPart.back() == '.') { targetPart.pop_back(); } // 5. 累加计算总和 int total = 0; for (char c : targetPart) { total += getComplexity(c); } std::cout << "目标字符的数值总和为:" << total << std::endl; return 0; }
关键说明
- 请将代码中的
test.txt替换为你自己的txt文件的实际路径,如果文件和代码在同一目录下直接写文件名即可。 - 你当前的
getComplexity函数也可以简化为一行实现:return (theCode >= 'A' && theCode <= 'E') ? (theCode - 'A' + 1) : 0;,功能完全一致,写法更简洁。 - 示例输入
ABCCCCE的计算结果为1+2+3*4+5=20,运行代码后会输出对应结果。
内容的提问来源于stack exchange,提问作者bean
相关产品推荐
相关产品推荐

