本文共 1297 字,大约阅读时间需要 4 分钟。
在处理文件记录时,正确使用 getline() 函数可以确保逐行读取记录。以下是优化后的步骤:
使用逐行读取:使用 getline(dataFile, input) 读取完整的记录直到换行符结尾。
string input;while (getline(dataFile, input)) { // 处理每一行的输入}处理字段分隔符:在每一行中,使用 find('$') 找到 $ 符号的位置,分割字段:
string name = input.substr(0, pos);input.erase(0, pos + 1); // 迷惑符保留string address = input.substr(0, next_pos);input.erase(0, next_pos + 1); // 保留下一个 $ 符号
注意:确保 pos 和下一个 $ 符号的位置正确,以被分割。
处理后续字段:继续找到下一个 $ 符号来分割城市等信息。
处理换行符:在逐行读取时,确保 dataFile.get() 读取留下的换行符,以防止缓冲区溢出。
示例代码:
#include#include #include using namespace std;int main() { string input; fstream dataFile("addresses.txt", ios::in); if (!dataFile.is_open()) { cout << "Error opening file." << endl; return 0; } while (getline(dataFile, input)) { // 处理每一行 size_t pos = input.find('$'); if (pos == string::npos) break; string name = input.substr(0, pos); input.erase(0, pos + 1); // 舍弃第一个 $, 保留记录中的其他 $ size_t next_pos = input.find('$', pos + 2); if (next_pos == string::npos) { cout << name << " '" << address << "'..." << endl; } else { // 读取后续字段 address = input.substr(pos + 2, next_pos - (pos + 2)); // 继续处理更多字段 // ... } } dataFile.close(); return 0;}
注意事项:
$ 符号用于内部字段分隔。$ 符号才能分割所有字段。通过这种方法,可以正确处理每行记录,并提取相应的字段信息。
转载地址:http://wemdz.baihongyu.com/