C++读取混合文字与数值的文本文件仅能提取首个整数后续无输出
问题原因
- 读取规则与文件结构不匹配:你固定每次读取3个字符串+1个int的逻辑仅适配第一行
- Account Number: 12345678的结构,其余行末尾值格式不符合该规则。比如第二行末尾是带$前缀的浮点数$875.00,不是纯int类型,读取时会直接让输入流inFile进入失败状态,后续所有读取操作全部中断,因此除了第一行的账号外没有其他输出。 - 未做特殊字符处理:金额字段前的
$属于非数值字符,直接读取数值会触发类型匹配错误。 - 缺失必要头文件:原代码未引入
<iostream>,控制台输出功能本身就存在未定义行为风险。
修复方案
核心思路改为逐行读取+单行独立解析,避免单行读取失败影响全局,同时单独处理带$的金额字段,修改后的可运行代码如下:
#include <fstream> #include <string> #include <iostream> #include <sstream> #include <cctype> using namespace std; int main() { ifstream inFile; int accNum; string accID; int games; double balance; double amountWon, amountLost; // 读取输入的账号 cout << "Please enter account number: "; cin >> accNum; // 拼接文件名 accID = "acc_" + to_string(accNum) + ".txt"; // 打开文件 inFile.open(accID); if (!inFile) { cout << "Account number does not exist.\n"; return 1; } string line; // 逐行读取文件 while (getline(inFile, line)) { istringstream lineStream(line); string prefix, key1, key2, valueStr; lineStream >> prefix >> key1 >> key2 >> valueStr; // 判断当前行的字段类型 if (key1 == "Account" && key2 == "Number:") { accNum = stoi(valueStr); cout << "账号:" << accNum << endl; } else if (key1 == "Current" && key2 == "Balance:") { // 去掉$符号再转double balance = stod(valueStr.substr(1)); cout << "当前余额:" << balance << endl; } else if (key1 == "Game" && key2 == "Played:") { games = stoi(valueStr); cout << "游玩次数:" << games << endl; } else if (key1 == "Total" && key2 == "Amount") { string extraKey; lineStream >> extraKey; if (extraKey == "Won:") { amountWon = stod(valueStr.substr(1)); cout << "总赢额:" << amountWon << endl; } else if (extraKey == "Loss:") { amountLost = stod(valueStr.substr(1)); cout << "总亏损:" << amountLost << endl; } } } inFile.close(); return 0; }
关键修改说明
- 新增
<iostream>、<sstream>、<cctype>头文件,补全输入输出、字符串流处理的依赖 - 用
getline逐行读取文件内容,某一行解析失败不会影响后续行的读取 - 对金额字段单独处理:截取
$符号后的字符串再转换为double类型,避免类型匹配错误 - 按字段名匹配解析逻辑,适配不同行的结构,可读性和可维护性更高
内容的提问来源于stack exchange,提问作者cheee808
相关产品推荐
相关产品推荐

