如何从文件读取含空格姓名及多类型数据(string/int/char/double)
处理含空格姓名的多类型数据提取方案
针对你需要从文件中逐行读取并提取带空格的姓名(string)、账号(int)、账户类型(char)、金额(double)的需求,核心思路是从行尾反向提取固定格式的无空格字段——因为账号、账户类型、金额都是无空格的,而姓名是行首到倒数第三个字段前的所有内容,这样就能适配所有带空格的姓名格式(比如"Mary Ann Smith"这种多空格的)。
下面给你几种常用编程语言的实现示例:
Python 实现
Python的字符串处理很灵活,我们可以先把行按空格分割成列表,然后取最后三个元素,前面的拼接成姓名:
with open('account_data.txt', 'r', encoding='utf-8') as file: for line in file: line = line.strip() # 去除首尾换行和空格 if not line: continue # 跳过空行 tokens = line.split() # 提取最后三个字段 amount = float(tokens[-1]) acc_type = tokens[-2] account_num = int(tokens[-3]) # 前面所有字段拼接为姓名 name = ' '.join(tokens[:-3]) # 验证输出 print(f"姓名: {name}, 账号: {account_num}, 类型: {acc_type}, 金额: {amount}")
注意:如果账户类型是单个字符(比如'S'代表储蓄,'C'代表支票),可以直接取
acc_type[0]确保是单个char。
C++ 实现
C++中可以用getline读取整行,然后从后往前查找空格定位字段:
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <algorithm> using namespace std; int main() { ifstream file("account_data.txt"); string line; while (getline(file, line)) { // 去除首尾空格 line.erase(line.begin(), find_if(line.begin(), line.end(), [](int ch) { return !isspace(ch); })); line.erase(find_if(line.rbegin(), line.rend(), [](int ch) { return !isspace(ch); }).base(), line.end()); if (line.empty()) continue; // 从后往前找第三个空格,分割姓名和后面的字段 size_t pos1 = line.find_last_of(' '); string amount_str = line.substr(pos1 + 1); line = line.substr(0, pos1); size_t pos2 = line.find_last_of(' '); string acc_type_str = line.substr(pos2 + 1); line = line.substr(0, pos2); size_t pos3 = line.find_last_of(' '); string account_num_str = line.substr(pos3 + 1); string name = line.substr(0, pos3); // 转换数据类型 int account_num = stoi(account_num_str); char acc_type = acc_type_str[0]; // 确保是单个字符 double amount = stod(amount_str); // 输出验证 cout << "姓名: " << name << ", 账号: " << account_num << ", 类型: " << acc_type << ", 金额: " << amount << endl; } file.close(); return 0; }
这个方法通过三次反向查找空格,精准分割出最后三个字段,前面的内容完整保留姓名的空格,适配所有姓名格式。
Java 实现
Java可以用split结合正则,或者从后处理字符串:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class AccountDataReader { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("account_data.txt"))) { String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; // 从后往前分割,找到最后三个空格的位置 int pos1 = line.lastIndexOf(' '); String amountStr = line.substring(pos1 + 1); line = line.substring(0, pos1); int pos2 = line.lastIndexOf(' '); String accTypeStr = line.substring(pos2 + 1); line = line.substring(0, pos2); int pos3 = line.lastIndexOf(' '); String accountNumStr = line.substring(pos3 + 1); String name = line.substring(0, pos3); // 类型转换 int accountNum = Integer.parseInt(accountNumStr); char accType = accTypeStr.charAt(0); double amount = Double.parseDouble(amountStr); // 打印结果 System.out.printf("姓名: %s, 账号: %d, 类型: %c, 金额: %.2f%n", name, accountNum, accType, amount); } } catch (IOException e) { e.printStackTrace(); } } }
关键注意事项
- 空行处理:一定要跳过空行,避免分割时出现数组越界错误。
- 数据类型校验:实际使用时最好加上异常捕获(比如
try-catch),防止文件中出现格式错误的行导致程序崩溃。 - 账户类型确保单个字符:如果文件中账户类型是单个字符,直接取第一个字符即可;如果是多字符(比如"SAVING"),则直接保留字符串即可。
内容的提问来源于stack exchange,提问作者Heather McIntyre
相关产品推荐
相关产品推荐

