如何在C++中使用getline()分割数据并实现指定格式输出
C++按~分割股票数据并格式化输出问题
输入文件内容
AMZN~Amazon.Com Inc~1402.05~+24.10~+1.75%~4854900~6806813~01/26/18~1523 AAPL~Apple Inc~171.51~+0.40~+0.23%~39128000~6710843~01/26/18~1224
原代码
#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { string line1[30]; string line2[30]; ifstream myfile("sp03HWstock.txt"); int a = 0; if(!myfile) { cout<<"Error opening output file"<<endl; system("pause"); return -1; } cout << left << setw(10) << "Stock Name " << left << setw(5) << " Value " << left << setw(8) << "Quantity " << left << setw(5) << " Total Worth " << endl; while(!myfile.eof()) { getline(myfile,line1[a],'~'); cout << left << setw(10); cout<< line1[a]; } }
当前错误输出
Stock Name Value Quantity Total Worth AMZN Amazon.Com Inc1402.05 +24.10 +1.75% 4854900 6806813 01/26/18 1523 AAPLApple Inc 171.51 +0.40 +0.23% 39128000 6710843 01/26/18 1224
期望输出
Stock Name Value Quantity Total Worth Amazon.Com Inc 1402.05 +24.10 6806813 Apple Inc 171.51 +0.23% 6710843
解决方案
修正后的代码如下:
#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { ifstream myfile("sp03HWstock.txt"); if (!myfile) { cout << "Error opening input file" << endl; system("pause"); return -1; } // 调整表头setw值,保证列对齐 cout << left << setw(25) << "Stock Name" << setw(10) << "Value" << setw(12) << "Quantity" << setw(15) << "Total Worth" << endl; string line; // 逐行读取,避免跨字段换行干扰 while (getline(myfile, line)) { size_t pos = 0; int fieldIndex = 0; string fields[9]; // 每行固定9个字段 // 分割当前行的所有字段 while ((pos = line.find('~')) != string::npos) { fields[fieldIndex++] = line.substr(0, pos); line.erase(0, pos + 1); } // 处理最后一个字段 if (!line.empty()) { fields[fieldIndex] = line; } // 清理字段前导空格,提取需要的字段 string stockName = fields[1]; stockName.erase(0, stockName.find_first_not_of(" ")); string value = fields[2]; string quantity = fields[3]; string totalWorth = fields[6]; // 按格式输出指定字段 cout << left << setw(25) << stockName << setw(10) << value << setw(12) << quantity << setw(15) << totalWorth << endl; } myfile.close(); system("pause"); return 0; }
关键修正说明
- 逐行分割字段:原代码直接按~读取所有字段,未区分行边界,导致换行逻辑混乱。改为先读整行再内存分割,避免换行符干扰。
- 精准提取目标字段:明确输入字段的索引对应关系,只输出需要的公司名、股价、涨跌数据、总市值,忽略冗余字段。
- 调整列宽对齐:根据内容长度重新设置
setw值,确保每个列的宽度足够容纳内容,实现结构化对齐。 - 清理冗余空格:输入行开头存在空格,分割后字段可能带前导空格,通过
erase去除保证输出整洁。 - 修复循环陷阱:原代码用
!myfile.eof()会导致最后一条记录重复读取,改用getline作为循环条件,逻辑更可靠。
内容的提问来源于stack exchange,提问作者klp
相关产品推荐
相关产品推荐

